使用查询参数在基于类的视图Django中过滤对象? [英] Filtering Objects in Class based view Django using Query parameters?

查看:34
本文介绍了使用查询参数在基于类的视图Django中过滤对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于类的通用视图 Listview 列出所有对象.

I am using Class-based Generic views Listview for listing all objects.

我的views.py:

My views.py:

class PostsList(ListView):
    model = Post
    template_name = "index.html"

我的Urls.py:

urlpatterns = [
    url(r'^$',PostsList.as_view(), name = "home"),
] 

这给了我所有帖子的列表.现在,我想根据 Post 模型的某些字段(例如 price )过滤/排序帖子.我需要自己写吗?如果是,我应该重写 PostsLists 类的哪种方法? def get def get_context 吗?

This gives me a list of all the posts. Now I want to filter/sort posts based on certain fields of Post Model, say price. Do I need to write this myself? If yes Which method of PostsLists class do I override ? def get, def get_context ?

我看到Listview的get方法定义如下.在其中,我可以直接将URL查询参数作为 ** kwargs 传递,或者必须在类中覆盖以下方法.

I see the get method for Listview defined as below. In it can I pass URL query-parameters as **kwargs directly or I have to overwrite the below method in my class.

def get(self, request, *args, **kwargs):
    ....

推荐答案

您可以覆盖get_queryset方法:

You can override the get_queryset method:

保留所有您可以在url kwargs中获得的参数的映射.

Keep a mapping of all the parameters that you can get in the url kwargs.

def get_queryset(self):
    queryset = Post.objects.all()

    if self.request.GET.get('price'):
        queryset = queryset.filter(price=self.request.GET.get('price'))
    return queryset

这篇关于使用查询参数在基于类的视图Django中过滤对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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