django rest在请求中获取嵌套数据

fnatzsnv  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(377)

我是刚用django和drf的。我有一个问题,要求一个模型与foreig键。
我有这3种型号:

class Order(models.Model):
       id = models.BigAutoField(primary_key=True)
       user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
       fecha = models.DateTimeField(auto_now=True)

       def __str__(self):
           return f"Orden : {self.id}"

    class Product(models.Model):
       id = models.BigIntegerField(primary_key=True)
       name = models.CharField(max_length=100)

       def __str__(self):
           return self.name

    class OrderDetail(models.Model):
       order = models.ForeignKey(Order, related_name="orders", on_delete=models.CASCADE)
       product = models.ForeignKey(Product, related_name="products", on_delete=models.CASCADE)

我想从详细信息中检索其产品的所有订单数据:
例子:

{ oders :[    
    { id : 1 ,
        user : 1 ,
        fecha : 01/02/2021,
        products : [ 
            { id : 1 , name : "product1" }
            { id : 2 , name : "prodcut2" }
     },
    { id : 2 ,
        user : 2 ,
        fecha : 10/02/2021,
        products : [ 
            { id : 3 , name : "product3" }
        ]
     }
    ]}

我的序列化程序是:

class ProductSerializer(serializers.ModelSerializer):
        class Meta:
            model = Product
            fields = ["id", "name"]

    class OrderDetailSerializer(serializers.ModelSerializer):
        class Meta:
            model = OrderDetail
            fields = ['order' ,'product']

    class OrderSerializer(serializers.ModelSerializer):
        products = OrderDetailSerializer(many=True)

        class Meta:
            model = Order
            fields = ['id', 'user', 'fecha' ,'products']

但我得到了一个错误:
attributeerror:尝试获取序列化程序“orderserializer”上字段“products”的值时获取attributeerror。序列化程序字段的名称可能不正确,并且与“order”示例上的任何属性或键都不匹配。原始异常文本为:“订单”对象没有属性“产品”。
我正在使用:

Django==3.2.5
djangorestframework==3.12.4
python==3.8

如果有人能帮助我,我将不胜感激

tct7dpnv

tct7dpnv1#

通过orderdetail模型添加多对多关系

class Order(models.Model):
       id = models.BigAutoField(primary_key=True)
       user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
       fecha = models.DateTimeField(auto_now=True)
       products = models.ManyToMany(Product, through="OrderDetail")

       def __str__(self):
           return f"Orden : {self.id}"

相关问题