【问题标题】:filter using Q object with dynamic from user?使用来自用户的动态 Q 对象进行过滤?
【发布时间】:2010-12-29 18:12:12
【问题描述】:

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

#......
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

**我的案例 tag_selected 是用户选中的复选框值 我的 url 传递的 tag_selected(is the list=1,2,3,...) 有问题

/?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])
                                                       ...
                                                        )

【问题讨论】:

    标签: django django-q


    【解决方案1】:

    这适用于单个和多个条件:

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

    【讨论】:

    • 全局名称'operator'未定义
    • 操作员可以。 idseq = tag_selected.split(',') print idseq #它显示:[u'2', u'3'] tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq)) 它提高一个错误。感谢您的帮助。:) int() 的无效文字,基数为 10:'2,3'
    • Thanksssssssssssss Ignacio Vazquez-Abran 它有效,我修复了它...... :)
    • 为此你需要from functools import reduce, import operator
    猜你喜欢
    • 2012-10-16
    • 2014-04-11
    • 2011-05-31
    • 2019-08-23
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多