搜索参数在 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', )
这将与前面的示例一样,但使用的代码更少。
有很多方法可以自定义此过滤,详情请查看here 和here。
还有一种方式可以申请filtering globally:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}