json 为什么Django Rest API序列化器没有正确序列化多对多字段

6tqwzwtp  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(126)

问题出在OrderProdSerializer类中,当我试图从OrderProd模型中获取一些信息时,我可以正确获取ID,但它忽略了其他字段,如“数量”和“日期”。
型号:

class Product(models.Model):
    ...
    name  = models.CharField(max_length=100, blank=True, null=True)
    price = models.DecimalField(max_digits=6,decimal_places=2)
    ...
  
class Order(models.Model):
    user    = models.ForeignKey("main.User", on_delete=models.CASCADE)
    details = models.ManyToManyField(Product, through="OrderProd")
    ...
    
    
class OrderProd(models.Model):
    product  = models.ForeignKey(Product, on_delete=models.CASCADE)
    order    = models.ForeignKey(Order  ,  on_delete=models.CASCADE)
    quantity = models.IntegerField(default=0)
    date     = models.DateTimeField(default=timezone.now)

字符串
OrderProd序列化器:

class OrderProdSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField( source='name')
    product_price= serializers.DecimalField(max_digits=20,decimal_places=2,source='price')
    class Meta:
        model=OrderProd
        fields=["id","product_name","quantity","product_price","date"]
        read_only_fields = ('id',)
  

      
class OrderSerializer(serializers.ModelSerializer):
    details = OrderProdSerializer(many=True)
    class Meta:
        model=Order
        fields=["id","details","created_date","order_date"]
        read_only_fields = ('id', )


结果:

[
    {
        "id": 1,
        "details": [
            {
                "id": 1,
                "product_name": "t-shirt",
                "product_price": "20.00",
            }
        ],
        "created_date": "2023-07-25T17:34:45Z",
        "order_date": null
    }
]


应该是:

[
    {
        "id": 1,
        "details": [
            {
                "id": 1,
                "product_name": "t-shirt",
                "product_price": "20.00",
                "quantity": 2 ,
                "date": "2023-07-25"
            }
        ],
        "created_date": "2023-07-25T17:34:45Z",
        "order_date": null
    }
]

8cdiaqws

8cdiaqws1#

谢谢你!我找到了解决方案:
解决方法是在细节中添加来源

details = OrderProdSerializer(many=True,read_only=True, source='orderprod_set')

字符串
我在OrderProdSerializer中做了一些更改

class OrderProdSerializer(serializers.ModelSerializer):
  
    product_name = serializers.CharField( source='product.name')
    product_price = serializers.CharField( source='product.price')

    class Meta:
        model=OrderProd
        fields=["id","order","quantity","date","product","product_name","product_price"]
        read_only_fields = ('id', )

相关问题