使用Q对象过滤使用动态的用户? [英] filter using Q object with dynamic from user?

查看:113
本文介绍了使用Q对象过滤使用动态的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的views.py中,我有一个方法:

In my views.py I have a method:

#......
def get_filter_result(self, customer_type, tag_selected):
        list_customer_filter=[]
        customers_filter = Customer.objects.filter(Q(type__name=customer_type),
                                                   Q(active=True),
                                                   Q(tag__id=tag_selected))

        for customer_filter in customers_filter:
                    customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
                    list_customer_filter.append(customer_filter)
        return list_customer_filter

**我的case tag_selected是用户检查的复选框
我有一个问题tag_selected(是list = 1,2,3,...)从我的URL传递

**My case tag_selected is the checkbox values that user checked I have a problems with tag_selected(is the list=1,2,3,...) that pass from my url

/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?

例如

if len(tag_selected)==1:
      customers_filter = Customer.objects.filter(Q(type__name=customer_type),
                                                       Q(active=True),
                                                       Q(tag__id=tag_selected))
else:
    customers_filter = Customer.objects.filter(Q(type__name=customer_type),
                                                       Q(active=True),
                                                       Q(tag__id=tag_selected[0])
                                                       Q(tag__id=tag_selected[1])
                                                       Q(tag__id=tag_selected[2])
                                                       ...
                                                        )


推荐答案

这适用于单和亩条件:

idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)

这篇关于使用Q对象过滤使用动态的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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