2016-01-22 155 views
0

由於數據庫設計的方式,圖像不與項目一起存儲。如何處理多個相關對象(在對象中嵌套)

這是因爲每個產品沒有設定的圖像數量。有些可能有1個圖像,其他可能有10個。

我希望我的API返回嵌套在其內部的內容。目前,我的代碼簡單地重複整個對象,當物品存在其他圖像時。

我使用Django的REST框架:

class ProductDetailView(APIView): 

    renderer_classes = (JSONRenderer,) 

    def get(self, request, *args, **kwargs): 

     filters = {} 
     for key, value in request.GET.items(): 
      key = key.lower() 
      if key in productdetailmatch: 
       lookup, val = productdetailmatch[key](value.lower()) 
       filters[lookup] = val 

     qset = (
      Product.objects 
      .filter(**filters) 
      .values('pk', 'brand') 
      .annotate(
       image=F('variation__image__image'), 
       price=F('variation__price__price'), 
       name=F('variation__name'), 
      ) 
     ) 

     return Response(qset) 

目前,有3個圖像指向它的一個項目將是這樣的:

[{ 
     "name": "Amplitiue jet black", 
     "brand": "Allup", 
     "price": "$1248", 
     "vari": "917439", 
     "image": "url1", 
    }, 
    { 
     "name": "Amplitiue jet black", 
     "brand": "Allup", 
     "price": "$1248", 
     "vari": "917439", 
     "image": "url", 
    }, 
    { 
     "name": "Amplitiue jet black", 
     "brand": "Allup", 
     "price": "$1248", 
     "vari": "917439", 
     "image": "url", 
    }, 

]

理想的情況下,它看起來應該像這樣,結合陣列內的所有圖像:

{ 
    "name": "Amplitiue jet black", 
    "brand": "Allup", 
    "price": "$1248", 
    "vari": "917439", 
    "images": [ 
     "url1", 
     "url2" 
     "url3" 
    ], 
} 

回答

0

您應該使用ListApiViewModelSerializer。不要將過濾放在get方法中,Django基於類的查看方式就是使用get_queryset

from rest_framework import serializers, generics 

class ImageSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Image 
     fields = ("url",) 

class ProductSerializer(serializers.ModelSerializer): 
    images = ImageSerializer(many=True) 
    class Meta: 
     model = Product 
     fields = ("name", "brand", "price", "vari", "images") 

class ProductListView(generics.ListAPIView): # it is not a details view 
    serializer_class = ProductSerializer 
    def get_queryset(self): 
     filters = {} 
     for key, value in self.request.GET.items(): 
      key = key.lower() 
      if key in productdetailmatch: 
       lookup, val = productdetailmatch[key](value.lower()) 
       filters[lookup] = val 
     return Product.objects.prefetch_related("images").filter(**filters) 

在JSON的圖像列表將是一個「URL」元素,而不僅僅是一個URL列表對象,但是這與REST標準更一致的反正。

+0

我需要在頂部導入一些東西嗎?我收到錯誤「name」ModelSerializer'未定義「。我已經從django.core導入序列化程序從rest_framework導入序列化程序 導入了序列化程序 – Ycon

+0

我已編輯以包含導入。順便提一下,它在我提供的文檔鏈接中 - 在開始使用它之前,您應該花時間閱讀Django REST框架文檔。 –

+0

不 - 還是與進口相同的問題。我已經通過django REST文檔閱讀,但仍然沒有運氣 - '模塊'對象沒有屬性'ModelSerializer' – Ycon