在Django Rest框架中输出不同的querisets

时间:2018-05-05 14:59:14

标签: django django-rest-framework

或许有点错误地提出了这个问题。一般来说,我不明白如何使用DRF传输各种对象集合。我需要列出所有的地方,最受欢迎的列表和列表是编辑的选择。我试图通过类比django观点来理解。

def places_list(request):
    places = Places.objects.all()
    editor_places = Places.objects.filter(editor_choice = True )
    popular_places = Places.objects.filter(most_popular = True )

    return render (request, "places/places_list.html",
                   {"places": places,
                    "editor_places": editor_places,
                    "popular_places": popular_places,
                    })

然后在模板中我显示3个带有我需要的参数的表。

MAke API

serializer.py

class PlaeceSerializer(ModelSerializer):

    url = HyperlinkedIdentityField(
    view_name='places_api:detail',
    lookup_field='pk'
    )
    class Meta:
        model = Places
        fields = (
            'url',
            'id',
            'main_photo',
            'name',           
        )

views.py

class PlacesListAPIView(ListAPIView):
    queryset = Places.objects.all()
    serializer_class = PlaeceSerializer

所以我有一个包含所有对象的json集合。如何正确制作样品?在views.py中还是可以像在前面处理数据一样?请分享您的经验。

2 个答案:

答案 0 :(得分:0)

您可以从ListAPIView覆盖def list。因此,您应该自定义响应,如:

  def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())

    page = self.paginate_queryset(queryset)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)

    places = self.get_serializer(queryset, many=True)
    editor = self.get_serializer(Places.objects.filter(editor_choice = True ), many=True)
    popular = self.get_serializer(Places.objects.filter(most_popular = True ), many=True)
    return Response({'places': places.data,'editor': editor.data,'popular': popular.data})

答案 1 :(得分:0)

class MultiFilterPlacesListView(ListAPIView):      msgstr“”“自定义查询集api视图。不实现分页”“”

 pagination_class = None
 queryset = Places.objects.all()
 slice_size = 10 

 def get_queryset(self):
     """Combine queries from new, editor choice and popular"""
     new_qs = self.queryset.filter(new_place=True)[:self.slice_size]
     editor_qs = self.queryset.filter(editor_choice=True)[:self.slice_size]
     popular_qs = self.queryset.filter(popular=True)[:self.slice_size]

     return new_qs.union(editor_qs, popular_qs, all=True)