2009-12-24 44 views
4

在我的views.py我有一個方法:從用戶動態過濾使用Q對象?

#...... 
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是複選框珍視用戶籤 我有一個tag_selected問題(在列表= 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]) 
                 ... 
                 ) 

回答

14

這適用於單個和多個條件:

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

@Ignacio Vazquez-Abran 你的代碼中的運算符是什麼? – kn3l

+0

stdlib中的模塊。 –

+0

未定義全局名稱'運營商' – kn3l