Negar37
Negar37

Reputation: 362

How can I make django query based on function input?

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

Upvotes: 0

Views: 37

Answers (1)

CJ4
CJ4

Reputation: 2535

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

Upvotes: 1

Related Questions