简体   繁体   中英

Django REST Framework: nested serializer not serializing

I am having bit of a pickle with Django REST Framework nested serializers.

I have a serializer called ProductSerializer. It is a serializers.ModelSerializer and correctly produces following output when used alone:

{'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. 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. There you see an OrderedDict instead.

Your renderer will take care of that and outputs the correct values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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