7

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

**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?

for example

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])
                                                       ...
                                                        )
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
tree em
  • 20,379
  • 30
  • 92
  • 130

1 Answers1

21

This works for both single and multiple conditions:

idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • global name 'operator' is not defined – tree em Dec 24 '09 at 08:01
  • okay for operator. idseq = tag_selected.split(',') print idseq #It display:[u'2', u'3'] tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq)) It raise an error.Thank for you help.:) invalid literal for int() with base 10: '2,3' – tree em Dec 24 '09 at 08:14
  • Thankssssssssssssss Ignacio Vazquez-Abran it works ,I fixed it ... :) – tree em Dec 24 '09 at 08:17
  • 4
    For this you'll need `from functools import reduce, import operator` – shacker Apr 01 '16 at 00:12