Reputation: 2384
When I query in Django and the query depends on filters I always do something like this:
if country:
country_arguments = {"country": country}
else:
country_arguments = {}
if supplier:
arguments = Q(supplier=supplier) | Q(supplier__parent=supplier)
else:
arguments = ""
Now I need a Q() in that argument. The argument should be something like this:
if country:
country_arguments = {"country": country}
else:
country_arguments = {}
if supplier:
arguments = Q(supplier=supplier) | Q(supplier__parent=supplier)
else:
arguments = ""
sites = (
sites.filter(
arguments,
**country_arguments,
).all())
But I get an error:
ValueError: not enough values to unpack (expected 2, got 0)
How can I do it as an **argument like:
arguments = Q(**{"supplier": supplier}) | Q(**{"supplier__parent": supplier})
Upvotes: 0
Views: 83
Reputation: 1343
You can do it like this:
if country:
query = Q(supplier=supplier) | Q(supplier__parent=supplier)
else:
query = Q()
sites.filter(query).all()
The best way would be to remove the else
clause:
sites = Site.objects.all()
if country:
query = Q(supplier=supplier) | Q(supplier__parent=supplier)
sites = sites.filter(query)
Upvotes: 1