2009-12-30 130 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)