在django-rest-framework中过滤ListAPIView

时间:2013-05-25 19:31:08

标签: django django-rest-framework

我正在使用ListAPIView,但我无法过滤结果。我的代码是:

class UserPostReadView(generics.ListAPIView):
    serializer_class = PostSerializer
    model = serializer_class.Meta.model
    queryset = model.objects.order_by('-post_time')
    lookup_field = 'poster_id'
    paginate_by = 100

在这种情况下,忽略lookup_field,但文档说它也支持此类。如果我尝试在通用视图上实现自定义get,则我不知道如何重新实现paginate_by。有什么想法吗?

2 个答案:

答案 0 :(得分:25)

我找到了解决方案

class UserPostsReadView(generics.ListAPIView):
    serializer_class = PostSerializer
    model = serializer_class.Meta.model
    paginate_by = 100
    def get_queryset(self):
        poster_id = self.kwargs['poster_id']
        queryset = self.model.objects.filter(poster_id=poster_id)
        return queryset.order_by('-post_time')

来源:http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-url

答案 1 :(得分:3)

我知道这已经很晚了,但是我写了一个扩展为ListAPIView的小应用程序并且更容易实现,请查看:

https://github.com/angvp/drf-lafv