Django中的控制查询集(过滤器,对象Q)?

时间:2009-12-30 05:23:31

标签: django 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))

任何人帮助提出实现我的方法比这更简单和灵活的想法? 如果它们的值缺失或等于无(没有值传递) 所以如果......其他......条件将控制很多时间,代码会更大..

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

感谢

2 个答案:

答案 0 :(得分: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 :(得分:1)

如果你想要AND所有查询(比如你的例子),你可以创建参数字典,然后用这个字典作为参数调用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)