在 Django Rest 中,无法序列化具有一对多映射的对象

In Django Rest, not able to serialize object which has One-to-Many mapping

我是 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 模型 classes:

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 以上型号:

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 table 中保存,而不在 CouponApplicableDays 中保存。

我知道,我在某处搞砸了,但我不知道在哪里。你们能看看上面的代码并告诉我如何解决这个问题吗?

你这里有一个列表 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 信号。