Reputation: 323
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?
Upvotes: 3
Views: 941
Reputation: 20996
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.
Upvotes: 5