我目前有以下输出。
{
"carts": [
{
"id": 1,
"product_id": 1,
"description": null,
"default": "Yes"
}
],
"categories": [
{
"id": 1,
"name": "Indoor Muscle Training",
"description": null
},
{
"id": 2,
"name": "Outdoor Muscle Training",
"description": null
}
]
}
我想附加一些对象列表,如下所示。这些产品现在必须是静态的。
{
"carts": [
{
"id": 1,
"product_id": 1,
"description": null,
"default": "Yes"
}
],
"categories": [
{
"id": 1,
"name": "Indoor Muscle Training",
"description": null,
"products":[
{
"id":1,
"name":"Product One"
},
{
"id":2,
"name":"Product Two"
}
]
},
{
"id": 2,
"name": "Outdoor Muscle Training",
"description": null,
"products":[
{
"id":1,
"name":"Product One"
},
{
"id":2,
"name":"Product Two"
}
]
}
]
}
这是我当前的文件 views.py
def home(request):
if request.method == 'GET':
default_cart = DefaultCart.objects.all()
categories = Category.objects.filter(parent_id=0)
serialized_default_cart = DefaultCartSerializer(default_cart, many=True)
serialized_categories = CategorySerializer(categories, many=True)
return Response({
'carts':serialized_default_cart.data,
'categories':serialized_categories.data,
})
serializers.py
class DefaultCartSerializer(serializers. HyperlinkedModelSerializer):
class Meta:
model = DefaultCart
fields = (
'id',
'product_id',
'description',
'default'
)
class CategorySerializer(serializers. HyperlinkedModelSerializer):
class Meta:
model = Category
fields = (
'id',
'name',
'description',
)
这些产品现在需要附加一个静态值。稍后,我将通过定义产品和类别之间的多对多关系来应用嵌套序列化器
答案 0 :(得分:0)
您可以使用 SerializerMethodField :
class CategorySerializer(serializers. HyperlinkedModelSerializer):
products = serializers.SerializerMethodField()
class Meta:
model = Category
fields = (
'id',
'name',
'description',
'products'
)
def get_products(self, obj):
return [
{
"id":1,
"name":"Product One"
},
{
"id":2,
"name":"Product Two"
}
]