如何在Django中动态向查询添加过滤器? [英] How to add filters to a query dynamically in Django?

查看:91
本文介绍了如何在Django中动态向查询添加过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的viewSet中,我正在执行查询,

In my viewSet I am doing a query,

queryset= Books.objects.all();

现在从ajax调用中,我从UI获取过滤器值,即作者的年龄,性别等总共有5个过滤器。

Now from an ajax call I get my filter values from UI i.e. age,gender, etc. of auther.There will be a total of 5 filters.

现在,我遇到的问题是如何向查询中添加过滤器(只有那些具有任何过滤器的过滤器

Now the problem which I ran into is how am I going to add filters to my query(only those filters which have any value).

我尝试的是检查单个过滤器值并进行查询,但是那样失败了,就像用户删除过滤器值或添加多个过滤器一样。
还有什么更好的建议可以做到这一点?

What I tried is I checked for individual filter value and did query, but that way it fails as if the user remove the filter value or add multiple filters. Any better suggestion how to accomplish this?

推荐答案

这里有一个更通用的建议。如果将过滤器作为 GET 参数传递,它将对您的查询集应用过滤器。如果您正在执行 POST 调用,只需更改代码中的名称即可。

Here's a bit more generic one. It will apply filters to your queryset if they are passed as the GET parameters. If you're doing a POST call, just change the name in the code.

import operator
from django.db.models import Q


def your_view(self, request, *args, **kwargs):
    # Here you list all your filter names
    filter_names = ('filter_one', 'filter_two', 'another_one', )

    queryset = Books.objects.all(); 
    filter_clauses = [Q(filter=request.GET[filter])
                      for filter in filter_names
                      if request.GET.get(filter)]
    if filter_clauses:
        queryset = queryset.filter(reduce(operator.and_, filter_clauses))

    # rest of your view

请注意,您可以在过滤器名称中使用查找表达式。例如,如果要过滤价格低于或等于过滤器中指定价格的图书,则可以只使用 price__lte 作为过滤器名称。

Note that you can use lookup expressions in your filters' names. For example, if you want to filter books with price lower or equal to specified in filter, you could just use price__lte as a filter name.

这篇关于如何在Django中动态向查询添加过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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