簡體   English   中英

如何使用 django-rest-framework 中的序列化程序將相似數據合並到自定義字段中?

[英]How to merge similar data into a custom field using serializers in django-rest-framework?

我有一個 api,它返回 material_id、material_name 及其 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"
                      },


    } 

我們將如何操作使用序列化器返回的數據,以及如何訪問進入序列化器的查詢集?

您想要的輸出不再是真正的 model 序列化程序,例如您完全放松了材料和商店之間的關系。

您應該考慮構建自己的字典,然后將其轉換為自定義 json 並將其作為響應傳遞,如下所述: https://stackoverflow.com/a/35019122/12197595

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM