问题出在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
}
]
型
1条答案
按热度按时间8cdiaqws1#
谢谢你!我找到了解决方案:
解决方法是在细节中添加来源
字符串
我在OrderProdSerializer中做了一些更改
型