Ahmed Wagdi
Ahmed Wagdi

Reputation: 4371

filter a query based on a value only if the value is not empty in django

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.

Edit

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

Answers (1)

Paweł Kordowski
Paweł Kordowski

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

Related Questions