我对 Django REST Framework 嵌套序列化程序感到有点困惑。
我有一个名为 ProductSerializer 的序列化器。它是一个serializers.ModelSerializer,单独使用时可以正确生成以下输出:
{'id': 1, 'name': '产品名称'}
我正在构建购物车/购物篮功能,目前我有以下类(class):
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')])]}
我期望的更像是:
{
'id': 1,
'products': [
{'id': 1, 'name': 'name of the product'}
{'id': 2, 'name': 'name of the product'}
]
}
你认为我错在哪里?
最佳答案
一切都很好。
很简单,为了保留顺序,DRF 不能使用基本字典,因为它们不保留顺序。在那里您会看到一个 OrderedDict。
您的渲染器将处理该问题并输出正确的值。
关于python - Django REST框架: nested serializer not serializing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42612760/