2009-12-30 170 views
0

基礎上,URL在Django中設置控制查詢(過濾器,對象Q)?

querydict = {customer_type:val1,tag:[], city:[],last_contact:valdate} 

show/?customer_type=All&tag=2,3&city=3&last_contact=29/12/2009 

我要過濾所作出的方法:

def get_filter_result(customer_type, tag_selected, city_selected, last_contact_filled): 
    if customer_type=has value: 
     I filter by this 
     #queryset = Customer.objects.filter(Q(type__name=customer_type)) 
    if tag = has value : 
     I filter by this 
     #queryset = Customer.objects.filter(Q(type__name=customer_type) 
               Q(type__name=tag)) 
    if city = has value: 
     I filter by this 
     #queryset = Customer.objects.filter(Q(type__name=customer_type) 
               Q(type__name=tag), 
               Q(type__name=city)) 
    if last_contact = has value: 
     I filter by this 
     #queryset = Customer.objects.filter(Q(type__name=customer_type) 
               Q(type__name=tag), 
               Q(type__name=city), 
               Q(type__name=last_contact)) 

人幫助出出主意來實現我的方法比這更簡單和靈活? 如果他們中的值丟失或等於無(沒有傳遞值) 所以如果...否則....條件將控制alots的時間和代碼將更大..

for example : 
     show/?customer_type=All&tag=&city=&last_contact= 
     show/?customer_type=All&tag=2,3&city=3&last_contact=29/12/2009 
     show/?customer_type=&tag=2,3&city=3&last_contact= 
     show/?customer_type=All&tag=2,3&city=&last_contact=29/12/2009 

感謝

回答

1
def get_filter_result(customer_type=None, tag_selected=None, city_selected=None, last_contact_filled=None): 
    qdict = {} 
    if customer_type is not None: 
     qdict['type__name'] = customer_type 
    if tag is not None: 
     <repeat as appropriate> 
    queryset = Customer.objects.filter(**qdict) 
1

如果你想和(在你的例子一樣)所有的疑問,您可以創建的參數字典,然後調用filter方法本字典作爲參數:

def get_filter_result(**kwargs): 
    params = {} 
    #delete items with empty strings 
    for key in kwargs: 
     if kwargs[key]: 
      params[key] = kwargs[key] 

    queryset = Customer.objects.filter(**params)