I want to make django query based on function input.I don't want to check input with if and else in 2 separate line and then make query like this:
def customer_number(mall,store=None):
if store :
customer = models.Customer.objects.filter(mall=mall,store=store)
else :
customer = models.Customer.objects.filter(mall=mall)
return customer.count
You can construct a lookup kwarg dictionary:
def customer_number(mall, store=None):
lookup_kwargs = {'mail': mail}
if store:
lookup_kwargs['store'] = store
return models.Customer.objects.filter(**lookup_kwargs).count()
Alternatively if you don't want any conditionals, you can construct the dict
and remove None
values:
def customer_number(mall, store=None):
lookup_kwargs = {'mail': mail, 'store': store}
lookup_kwargs = {k: v for k, v in lookup_kwargs.items() if v is not None}
return models.Customer.objects.filter(**lookup_kwargs).count()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.