在Django-rest-framework中过滤ListAPIView [英] Filtering ListAPIView in django-rest-framework

查看:438
本文介绍了在Django-rest-framework中过滤ListAPIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using ListAPIView, but I can't filter the results. My code is:

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 。有任何想法吗?

In this case, lookup_field is ignored, but the documentation says that it's supported for this class too. If I try to implement a custom get over a generic view, I don't know how to reimplement paginate_by. Any ideas?

推荐答案

我找到了解决方案

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

这篇关于在Django-rest-framework中过滤ListAPIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆