1
我有點Django REST框架嵌套序列化程序的泡菜。Django REST框架:嵌套序列化程序沒有序列化
我有一個名爲ProductSerializer的序列化程序。這是一個serializers.ModelSerializer和單獨使用時產生正確的輸出如下:
{'id': 1, 'name': 'name of the product'}
我建立一個購物車/籃的功能,爲此,我現在有下面的類:
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)
以上產品是型號。型號。現在,當我做
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'}
]
}
你以爲我要去哪裏錯了嗎?
好熱的該死的。在這裏,我對django詛咒的是比我實際要求的更好的工作。證實與json.dumps是的,你的先生,確實是對的:)謝謝! – xtrom0rt