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)
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With