0

基于 URL

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

谢谢

4

2 回答 2

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)
于 2009-12-30T09:22:47.400 回答
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)
于 2009-12-30T09:23:49.130 回答