如何在Django REST Framework中向GET请求添加搜索参数?

在通读并完成
Django REST Framework tutorial之后,如何在GET请求上实现过滤器并不是完全明显的.例如,
ListAPIView非常适合查看数据库中Model的所有实例.但是,如果我想限制结果(例如,对于Book模型,我可能希望按发布日期或作者等限制结果).似乎最好的方法是创建一个自定义的Serializer,View等,并基本上手工编写所有内容.

有没有更好的办法?

最佳答案 搜索参数根据django-rest-framework称为过滤器参数.有很多方法可以应用过滤,请查看
documentation.

在大多数情况下,您只需要覆盖视图,而不是序列化程序或任何其他模块.

一种显而易见的方法是覆盖视图的查询集.例:

# access to /api/foo/?category=animal

class FooListView(generics.ListAPIView):
    model = Foo
    serializer_class = FooSerializer

    def get_queryset(self):
        qs = super(FooListView, self).get_queryset()
        category = self.request.query_params.get("category", None)
        if category:
            qs = qs.filter(category=category)
        return qs

但是,django-rest-framework允许使用django-filter自动执行此类操作.

首先安装它:

pip install django-filter

然后在视图中指定要过滤的字段:

class FooListView(generics.ListAPIView):
    model = Foo
    serializer_class = FooSerializer
    filter_fields = ('category', )

这将执行相同的操作,如前面的示例所示,但使用的代码较少.

有许多方法可以自定义此过滤,有关详细信息,请参阅herehere.

还有一种方法可以申请filtering globally

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}
点赞