Control Query set in Django (filter,object Q)?
Base On URL
querydict = {customer_type:val1,tag:[], city:[],last_contact:valdate}
show/?customer_type=All&tag=2,3&city=3&last_contact=29/12/2009
I am going to filter by made the method:
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))
Anybody Help give an idea to implement my method more simple and flexible than this? if value of them are missing or equal None(No value is passed) so if... else.... condition will control alots of time and code will be larger..
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
thanks
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)
If you want to AND all your queries (like in your example), you can create dictionary of parameters, and then call filter
method with this dictionary as an argument:
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)
精彩评论