我在Django REST Framework嵌套序列化器方面遇到了一点麻烦。
我有一个名为ProductSerializer的序列化器。它是serializers.ModelSerializer类型,仅使用它时可以正确生成以下输出:
{'id': 1, 'name': '产品名称'}
我正在构建购物车/篮子功能,目前有以下类:
class BasketItem:
def __init__(self, id):
self.id = id
self.products = []
和一个序列化器:
class BasketItemSerializer(serializers.Serializer):
id = serializers.IntegerField()
products = ProductSerializer(many=True)
我有一个测试案例,涉及以下代码:
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)
上面的产品是一个models.Model模型。现在,当我执行
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'}
]
}
你认为我哪里做错了?