我是Django Rest框架的初学者。我想实现一对多的对象映射,如下面的json schema:
{
"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 Model类:
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
使用优惠券序列化程序保存数据时。它仅保存在优惠券表中而不是CouponApplicableDays。
我知道,我搞砸了某个地方,但我不知道在哪里。你们可以查看上面的代码并告诉我如何解决这个问题?
答案 0 :(得分:1)
这里有一个列表
coupon_applicable_days_data = validated_data.pop("coupon_applicable_days")
迭代列表并创建对象,如下所示:
for applicable_day in coupon_applicable_days_data:
CouponApplicableDays.objects.create(coupon=coupon, **applicable_day)
或使用bulk_create
方法
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#bulk-create
CouponApplicableDays.objects.bulk_create(
[CouponApplicableDays(coupon=coupon, **aplicable_day)
for applicable_day in coupon_applicable_days_data]
)
请注意,bulk_create
不会触发pre_save/post_save
信号。