【发布时间】:2018-01-15 23:39:10
【问题描述】:
我是 Django Rest 框架的初学者。我想实现一对多对象映射,如以下 json 模式:
{
"from_date": "2017-08-06T12:30",
"to_date": "2017-08-06T12:30",
"coupon_name": "WELCOME100",
"min_booking_value": 150,
"applicable_days": [
{
"from_time": "13:00",
"to_time": "15:00",
"applicable_day": 2
},
{
"from_time": "16:00",
"to_time": "18:00",
"applicable_day": 3
}
]
}
对于上述 json 架构,我创建了以下 Django 模型类:
class Coupon(models.Model):
coupon_id = models.AutoField(primary_key=True)
from_date = models.DateTimeField()
to_date = models.DateTimeField()
coupon_name = models.TextField()
min_booking_value = models.FloatField()
def __unicode__(self):
return 'Coupon id: ' + str(self.coupon_id)
class CouponApplicableDays(models.Model):
from_time = models.TimeField()
to_time = models.TimeField()
applicable_day = models.IntegerField()
以及以下型号的序列化程序类:
class CouponApplicableDaysSerializer(serializers.ModelSerializer):
class Meta:
model = CouponApplicableDays
fields = ('from_time', 'to_time', 'applicable_day')
class CouponSerializer(serializers.ModelSerializer):
coupon_applicable_days = CouponApplicableDaysSerializer(required=True, many=True)
class Meta:
model = Coupon
fields = ('coupon_id', 'from_date', 'to_date', 'coupon_name', 'min_booking_value', 'coupon_applicable_days',)
def create(self, validated_data):
coupon_applicable_days_data = validated_data.pop("coupon_applicable_days")
coupon = Coupon.objects.create(**validated_data)
CouponApplicableDays.objects.create(coupon=coupon, **coupon_applicable_days_data)
return coupon
当我使用优惠券序列化程序保存数据时。它只保存在 Coupon 表中,而不保存在 CouponApplicableDays 中。
我知道,我在某个地方搞砸了,但我不知道在哪里。你们能看看上面的代码并告诉我如何解决这个问题吗?
【问题讨论】:
标签: python python-2.7 django-models django-rest-framework django-serializer