如何在Django REST Framework中将搜索参数添加到GET请求? [英] How to add search parameters to GET request in Django REST Framework?

查看:82
本文介绍了如何在Django REST Framework中将搜索参数添加到GET请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通读并完成 Django REST Framework教程之后,目前尚不完全清楚如何对GET请求实施过滤器.例如, ListAPIView 非常适合查看所有实例数据库中模型的模型.但是,如果我想限制结果(例如,对于 Book 模型,我可能想按出版日期或作者等来限制结果).看来最好的方法是创建一个自定义的Serializer,View等,并基本上手动编写所有内容.

有更好的方法吗?

解决方案

根据django-rest-framework,搜索参数称为过滤器参数.应用过滤的方法有很多,请查看文档.>

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

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

 #访问/api/foo/?category = animalFooListView(generics.ListAPIView)类:型号= Fooserializer_class = FooSerializerdef get_queryset(self):qs = super(FooListView,self).get_queryset()category = self.request.query_params.get("category",无)如果类别:qs = qs.filter(类别=类别)返回qs 

但是,django-rest-framework允许自动使用此处以获取详细信息.

还有一种方法可以全局应用全局过滤:

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

After having read through and completed the Django REST Framework tutorial, it is not completely obvious how one would implement a filter on a GET request. For example, ListAPIView is great for viewing all the instances of a Model in your database. However, if I wanted to limit the results (e.g. for a Book model, I might want to limit the results by publication date or author, etc.). It seems the best way to do this would be to create a custom Serializer, View, etc. and basically write everything by hand.

Is there a better way?

解决方案

Search parameters are called filter parameters in terms of django-rest-framework. There are many ways to apply the filtering, check the documentation.

In most cases, you need to override just view, not serializer or any other module.

One obvious approach to do it, is to override view's queryset. Example:

# 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

But, django-rest-framework allows to do such things automatically, using django-filter.

Install it first:

pip install django-filter

Then specify in your view, by what fields you want to filter:

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

This will do the same, as in previous example, but less code used.

There are many ways to customize this filtering, look here and here for details.

There is also a way to apply filtering globally:

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

这篇关于如何在Django REST Framework中将搜索参数添加到GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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