2016-01-22 92 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