[英]How to merge similar data into a custom field using serializers in django-rest-framework?
I have an api which returns the material_id,material_name and it's store_id (foreign key) and store_name and it also has a search backend.我有一个 api,它返回 material_id、material_name 及其 store_id(外键)和 store_name,它还有一个搜索后端。 So i want to return all the material_name and material_id's on one key material and similarly all the store fields in the key store.
因此,我想返回一个密钥材料上的所有材料名称和材料 ID,以及密钥存储中的所有存储字段。
So i've tried the code below所以我尝试了下面的代码
class MaterialSuggestions(generics.ListAPIView):
search_fields = ['name', 'shape', 'color', 'material_type',
'surface_type', 'store__name']
filter_backends = (filters.SearchFilter,)
queryset = Material.objects.all()
serializer_class = MaterialSuggestionsSerializer
class MaterialSuggestionsSerializer(serializers.ModelSerializer):
class Meta:
model = Material
fields = ('material','store')
material = serializers.SerializerMethodField('get_material')
store = serializers.SerializerMethodField('get_store')
def get_material(self,obj):
return {'material_id':obj.id,'material_name':obj.name}
def get_store(self,obj):
return {'store_id':obj.store.id,'store_name':obj.store.name}
when i call the api i get something like this:当我调用 api 时,我得到如下信息:
{
"material": {
"material_id": 14,
"material_name": "test"
},
"store": {
"store_id": 28,
"store_name": "test1"
}
},
{
"material": {
"material_id": 13,
"material_name": "test3"
},
"store": {
"store_id": 29,
"store_name": "test2"
}
}
]
This is what I would ideally want to return.这就是我理想的回报。
{
"material": [ {
"material_id": 14,
"material_name": "test"
},
{
"material_id": 13,
"material_name": "test3"
}
]
"store": [ {
"store_id": 28,
"store_name": "test1"
},
{
"store_id": 29,
"store_name": "test2"
}
]
}
or Even this would be great或者即使这也很棒
{
"material": {
"material_id": 14,13
"material_name": "test","test3"
},
"store": {
"store_id": 28,29
"store_name": "test1","test2"
},
}
How would we manipulate the data we are returning using a serialzer and how can we access the queryset which is going into the serializer?我们将如何操作使用序列化器返回的数据,以及如何访问进入序列化器的查询集?
Your desired outputs are no longer really model serializers as for example you completely loose the relationships between materials and stores.您想要的输出不再是真正的 model 序列化程序,例如您完全放松了材料和商店之间的关系。
You should instead consider building your own dictionary, then converting it to a custom json and just pass it as a response as explained here: https://stackoverflow.com/a/35019122/12197595您应该考虑构建自己的字典,然后将其转换为自定义 json 并将其作为响应传递,如下所述: https://stackoverflow.com/a/35019122/12197595
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.