首页 > 解决方案 > 如何使用 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"
                      },


    } 

我们将如何操作使用序列化器返回的数据,以及如何访问进入序列化器的查询集?

标签: pythondjangodjango-modelsdjango-rest-frameworkdjango-serializer

解决方案


您想要的输出不再是真正的模型序列化器,例如您完全松散了材料和商店之间的关系。

相反,您应该考虑构建自己的字典,然后将其转换为自定义 json 并将其作为响应传递,如下所述: https ://stackoverflow.com/a/35019122/12197595


推荐阅读