简体   繁体   中英

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 .

How about creating a dict with filter parameters:

filter_params = {}
if the_type != "":
    filter_params['type'] = the_type
rows = Attendance.objects.filter(**filter_params)

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM