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

时间:2016-10-01 12:44:27

标签: django serialization django-rest-framework

我正在处理优惠券销售网站。我有以下型号,(不包括额外的细节)。

    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": {}
                }
            ]
        }

1 个答案:

答案 0 :(得分:0)

我认为您应该将serializers.ModelSerializerCouponSerializer中的OrderDetailSerializer替换为serializer.Serializer,而不仅仅是OrderSerializer - 就像您在created_at中所做的那样。

之后您会收到一些错误,因为您的模型(优惠券和OrderDetail)不会声明任何updated_atis_activeMeta字段。因此,您应该将这些字段添加到模型中,或者从两个序列化程序类中<div class="container"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-3"> </div> <div class="col-lg-9 col-md-9 col-sm-9 white"> <div class="row"> <div class="col-lg-9 col-md-9 col-sm-8 col-xs-12 rghtpd"><style>.rghtpd{padding-right: 0px !important; width:583px;}</style> <div class="title">Contact us</div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div class="contact_item expanded"> <div class="head"> <div class="name">California office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info" style="display: block;"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> One Embarcadero Center Suite 500, San Fransisco, 94111, CA </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> (415) 639-3001 </li> </ul> <div class="clearfix"></div> </div> </div> <div class="contact_item"> <div class="head"> <div class="name">Florida office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info" style="display: none;"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> 9600 Koger Blvd. Suite 225, St. Petersburg, 33702, FL </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> (727) 578-2800 </li> </ul> <div class="clearfix"></div> </div> </div> <div class="contact_item"> <div class="head"> <div class="name">London office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info" style="display: none;"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> Lloyd's Building, Gallery 4 12 Leadenhall St., London, EC3V 1LP, England </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> (0207) 101-9395 </li> </ul> <div class="clearfix"></div> </div> </div> <div class="contact_item "> <div class="head"> <div class="name">myName office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> 123 Fake st , Springfield, 12345, OH </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> 555 </li> </ul> <div class="clearfix"></div> </div> </div> </div> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div class="contact_item expanded"> <div class="head"> <div class="name">Ohio office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info" style="display: block;"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> 4449 Easton Way 2nd Floor, Columbus, 43219, OH </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> (614)526-8754 </li> </ul> <div class="clearfix"></div> </div> </div> <div class="contact_item"> <div class="head"> <div class="name">Pennsylvania office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info" style="display: none;"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> One International Plaza Suite 550, Philadelphia, 19113, PA </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> (215) 279-5845 </li> </ul> <div class="clearfix"></div> </div> </div> <div class="contact_item "> <div class="head"> <div class="name">Texas office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> 950 Echo Lane Suite 200, Houston, 77024, TX </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> (832) 586-0301 </li> </ul> <div class="clearfix"></div> </div> </div> <div class="contact_item "> <div class="head"> <div class="name">WASH office<span class="plus">+</span> <span class="minus">-</span></div> </div> <div class="info"> <ul> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/marker.png"></div> 1100 Dexter Avenue North Suite 100, Seattle, 98109, WA </li> <li> <div class="icon"><img alt="" src="//lig.azureedge.net/public/UK/Content/Images/phone.png"></div> (253)271-9692 </li> </ul> <div class="clearfix"></div> </div> </div> </div> </div> </div> $(".contact_item .head").click(function () { if ($(this).parent('div').hasClass('expanded')) { $(this).next('div').slideUp(); $(this).parent('div').removeClass('expanded'); $(".info").each(function(i , obj){ console.log($(obj)) $(obj).removeClass('expanded'); $(obj).slideUp(); }) } else { $(".info").each(function(i , obj){ console.log($(obj)) $(obj).removeClass('expanded'); $(obj).slideUp(); }) $(this).parent('div').addClass('expanded'); $(this).next('div').slideDown(); } }); .contact_item{ background-color: #bdc3c7; color: white; margin-bottom: 10px } 的列表中删除它们。但之后它按预期工作。