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))

私のメソッドをこれよりもシンプルで柔軟に実装するためのアイデアを手伝ってくれる人はいますか? それらの値が欠落しているか、None(値が渡されない)に等しい場合、if... else....条件は多くの時間を制御し、コードは大きくなります..

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 に答える