Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrease the number of elif blocks

I 'm trying to do a filter based on the following queryparams.

How can I decrease the lines of code:

if fridge == 'true' and toilet == 'true' and side_window == 'true':
    queryset = queryset.filter(toilet=True, fridge=True, sun_side_window=True)
elif fridge == 'true' and toilet == 'true':
    queryset = queryset.filter(toilet=True, fridge=True)
elif fridge == 'true' and side_window == 'true':
    queryset = queryset.filter(sun_side_window=side_window.capitalize(), fridge=fridge.capitalize())
elif toilet == 'true' and side_window == 'true':
    queryset = queryset.filter(sun_side_window=side_window.capitalize(), toilet=toilet.capitalize())
elif fridge == 'true':
    queryset = queryset.filter(fridge=fridge.capitalize())
elif toilet == 'true':
    queryset = queryset.filter(toilet=toilet.capitalize())
elif side_window == 'true':
    queryset = queryset.filter(sun_side_window=True)
like image 373
Zorig Avatar asked Jul 21 '17 11:07

Zorig


1 Answers

I am assuming that by 'true'.capitalize(), you mean the Boolean value True, and not the string 'True'

First, convert 'true' to True. Then, build a dictionary that holds the keyword arguments to be passed to queryset.filter. I am doing these two steps in one single dictionary comprehension:

vars = {'fridge': fridge, 'toilet': toilet, 'side_window': side_window}
kwargs = {kw: True for kw in vars if vars[kw] == 'true'}

If you are unfamiliar with the comprehensions, this is equivalent to:

kwargs = {}
for kw in vars:
    if vars[kw] == 'true':
        kwargs[vars] = True

Then unpack this dictionary, and pass it to queryset.filter:

queryset = queryset.filter(**kwargs)

Unpacking the dictionary is equivalent to passing its key/value pairs as keyword arguments to the function.

f(a=1, b=2)
# is equivalent to
kw = {'a': 1, 'b': 2}
f(**kw)

As a side note, I don't know of queryset, but it looks like a module. If so, I would not suggest to reassign the result of queryset.filter to queryset...

like image 85
Right leg Avatar answered Nov 06 '22 21:11

Right leg