6

私の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(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])
                                                       ...
                                                        )
4

1 に答える 1

18

これは、単一の条件と複数の条件の両方で機能します。

idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)
于 2009-12-24T07:46:59.780 に答える