3

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well hot damn. And here I was cussing at django that was doing a better job than I actually asked of it. Confirmed with json.dumps that yes, you sir, are indeed right :) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.