python - 如何使用 django-rest-framework 中的序列化程序将相似数据合并到自定义字段中?
问题描述
我有一个返回 material_id、material_name 的 api,它是 store_id(外键)和 store_name,它还有一个搜索后端。因此,我想返回一个密钥材料上的所有材料名称和材料 ID,以及密钥存储中的所有存储字段。
所以我尝试了下面的代码
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}
当我调用 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"
}
}
]
这就是我理想的回报。
{
"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"
}
]
}
或者即使这也很棒
{
"material": {
"material_id": 14,13
"material_name": "test","test3"
},
"store": {
"store_id": 28,29
"store_name": "test1","test2"
},
}
我们将如何操作使用序列化器返回的数据,以及如何访问进入序列化器的查询集?
解决方案
您想要的输出不再是真正的模型序列化器,例如您完全松散了材料和商店之间的关系。
相反,您应该考虑构建自己的字典,然后将其转换为自定义 json 并将其作为响应传递,如下所述: https ://stackoverflow.com/a/35019122/12197595
推荐阅读
- android - 在 Firebase 文档中的列表开头插入新的孩子
- excel - VB.Net COMException 尝试将数据从一个 Excel 文档粘贴到另一个
- flutter - 如何减少 Flutter Web 应用程序的加载时间
- php - 如何在 woocommerce 计费字段之间插入元素?
- selenium-webdriver - 范围报告版本 4 - 为所有已执行的测试用例创建两个范围报告而不是一个 html 报告
- python - 为什么这条sql语句超级慢?
- javascript - 获取并写入 js 文件中的 json 文档
- flutter - 如何设置 Flutter showMenu 起点
- matlab - 我试图使用 LSB 将图像隐藏在另一个图像中,但生成的图像以高对比度出现
- c++ - 无法打印正确的结果