简体   繁体   English

Django REST Framework:嵌套序列化程序未序列化

[英]Django REST Framework: nested serializer not serializing

I am having bit of a pickle with Django REST Framework nested serializers. 我对Django REST Framework嵌套序列化程序有点不满意。

I have a serializer called ProductSerializer. 我有一个称为ProductSerializer的序列化器。 It is a serializers.ModelSerializer and correctly produces following output when used alone: 它是一个serializers.ModelSerializer,单独使用时会正确产生以下输出:

{'id': 1, 'name': 'name of the product'}

I'm building a shopping cart / basket functionality, for which I currently have the following class: 我正在构建一个购物车/购物篮功能,目前,我有以下课程:

class BasketItem:

    def __init__(self, id):
        self.id = id
        self.products = []

and a serializer: 和一个序列化器:

class BasketItemSerializer(serializers.Serializer):
   id = serializers.IntegerField()
   products = ProductSerializer(many=True)

I have a test case involving following code: 我有一个涉及以下代码的测试用例:

products = Product.objects.all()  # gets some initial product data from a test fixture

basket_item = BasketItem(1)  # just passing a dummy id to the constructor for now
basket_item.products.append(products[0])
basket_item.products.append(product1[1])

ser_basket_item = BasketItemSerializer(basket_item)

Product above is a models.Model. 上面的产品是models.Model。 Now, when I do 现在,当我做

print(ser_basket_item.data)

{'id': 1, 'products': [OrderedDict([('id', 1), ('name', 'name of the product')]), OrderedDict([('id', 2), ('name', 'name of the product')])]}

What I expect is more like: 我期望的更像是:

{
    'id': 1,
    'products': [
        {'id': 1, 'name': 'name of the product'}
        {'id': 2, 'name': 'name of the product'}
    ]
}

Where do you think I'm going wrong? 您认为我在哪里错了?

Everything's fine. 一切安好。

It's simply that in order to preserve the order DRF can't use basic dictionaries as they don't keep the order. 只是为了保留订单,DRF不能使用基本字典,因为它们不保留订单。 There you see an OrderedDict instead. 在那里,您看到的是OrderedDict。

Your renderer will take care of that and outputs the correct values. 渲染器将​​处理此问题并输出正确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM