[Django]-How to avoid too many if – else blocks in python

6👍

Internally, the keyword arguments you’re passing to the function are just a dict. So build it yourself and pass it to the function using the **name syntax:

args = {}

args['name__contains'] = cd['name']

if cd['subject'] is not None:
    args['subject'] = cd['subject']
if cd['school'] != '':
    args['school'] = cd['school']
if cd['price']:
    args['price'] = cd['price']

files = File.objects.filter(**args)
return render(request, 'search.html', {'files': files, 'request': request})

0👍

Build a dict with the keyword args for your call to filter(), then pass it using the **kwargs syntax.

Leave a comment