【问题标题】:In Django Rest, not able to serialize object which has One-to-Many mapping在 Django Rest 中,无法序列化具有一对多映射的对象
【发布时间】: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


    【解决方案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 信号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 2015-07-11
      • 1970-01-01
      • 2016-01-19
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      相关资源
      最近更新 更多