Reputation: 4371
I need to filter a query based on a variable but only if this var is not empty ... here is what I have tried :
rows = Attendance.objects.filter(type= the_type if the_type != "" else '*')
the problem is in the part else '*'
I have tried to remove else, but it won't work as it is required to use an else after if in the ternary operator
, also tried else pass
but it gives me an error.
I could use if
outside of the queryset, but I have more than one dynamic variable that I will use in the same query, so wrapping it inside an if statement won't work well
.
Upvotes: 0
Views: 700
Reputation: 2768
How about creating a dict with filter parameters:
filter_params = {}
if the_type != "":
filter_params['type'] = the_type
rows = Attendance.objects.filter(**filter_params)
?
Upvotes: 2