gpt4 book ai didi

django - djangorest框架中的反向嵌套关系序列化

转载 作者:行者123 更新时间:2023-12-02 20:44:15 27 4
gpt4 key购买 nike

我正在开发一个交易/优惠券销售网站。我有以下型号(不包括额外的细节)。

    class Order(models.Model):

email = models.EmailField(max_length=200, null=False)
phone_number = models.CharField(max_length=10, null=False)
shipping_address = models.TextField(blank=True,null=True)
coupon_code = models.CharField(max_length=20,null=True,blank=True)
gross_total = models.FloatField(default=0.0)

class Meta:
db_table = 'order'


class OrderDetail(models.Model):
order = models.ForeignKey(Order,related_name='order_details')
package = models.ForeignKey(Package)
quantity = models.IntegerField(null=False)
unit_price = models.FloatField(default=0.0)

class Meta:
db_table = 'order_detail'




class Coupon(models.Model):
order_detail = models.ForeignKey(OrderDetail,related_name='coupons')
code = models.CharField(max_length=200, null=False, unique=True)
maximum_usage_count = models.IntegerField(null=False)
used_count = models.IntegerField(default=0)
valid_from = models.DateTimeField(null=False)
valid_to = models.DateTimeField(null=False)

class Meta:
db_table = 'coupon'

我的序列化器是,

    class CouponSerializer(serializers.Serializer):
class Meta:
model = Coupon
fields = ['id', 'code', 'maximum_usage_count', 'used_count', 'valid_from', 'valid_to', 'created_at',
'updated_at', 'is_active']


class OrderDetailSerializer(serializers.Serializer):
coupons = CouponSerializer(read_only=True)

class Meta:
model = OrderDetail
fields = ['id', 'package', 'quantity', 'unit_price', 'created_at', 'updated_at', 'is_active']


class OrderSerializer(serializers.ModelSerializer):
order_details = OrderDetailSerializer(read_only=True,many=True)

class Meta:
model = Order
fields = ['id','email', 'phone_number', 'shipping_address', 'coupon_code', 'gross_total','order_details']

在我的 listapiview 中,为了获取所有订单,我指定了订单序列化程序。 API 工作正常,但无法序列化反向关系模型。我收到以下回复。

{
"id": 31,
"email": "ff@b.com",
"first_name": "ff",
"last_name": "ff",
"phone_number": "ff",
"shipping_address": "",
"coupon_code": "",
"gross_total": 1.0,
"payment_method": "ONLINE",
"order_status": "PLACED",
"created_at": "2016-10-01T17:26:00.432000",
"updated_at": "2016-10-01T17:48:50.797000",
"is_active": true,
"order_details": [
{
"coupons": {}
},
{
"coupons": {}
},
{
"coupons": {}
}
]
}

最佳答案

我认为您应该将 CouponSerializerOrderDetailSerializer 中的继承类替换为 serializers.ModelSerializer,而不仅仅是 serializer.Serializer - 就像您在 OrderSerializer 中所做的那样。

之后您会收到一些错误,因为您的模型(Coupon 和 OrderDetail)未声明任何 created_atupdated_atis_active 领域。因此,您应该将这些字段添加到模型中,或从两个序列化器类的 Meta 列表中删除它们。但之后它就按预期工作了。

关于django - djangorest框架中的反向嵌套关系序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com