0

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

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.