【发布时间】:2018-05-22 14:33:31
【问题描述】:
我有以下序列化程序:我正在尝试添加键:值表示。在stackoverflow上搜索后,根据Return list of objects as dictionary with keys as the objects id with django rest framerwork的答案,我已经覆盖了to_representation方法。
class IngredientListSerializer(ModelSerializer):
class Meta:
model = Ingredient
fields = '__all__'
def to_representation(self, data):
res = super(IngredientListSerializer, self).to_representation(data)
return {res['id']: res}
我的看法是:
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all()
serializer_class = IngredientListSerializer
输出如下:
"results": [
{
"172": {
"id": 172,
"name": "rice sevai",
}
},
{
"218": {
"id": 218,
"name": "rocket leaves",
}
}
]
我正在寻找的输出是:
"results": {
"172": {
"id": 172,
"name": "rice sevai",
},
"218": {
"id": 218,
"name": "rocket leaves",
}
}
【问题讨论】:
标签: django django-rest-framework