仅当django中的值不为空时,才根据该值筛选查询



我需要根据变量过滤查询,但前提是该变量不为空。。。这是我尝试过的:

rows = Attendance.objects.filter(type= the_type if the_type != "" else '*')

问题出在部分else '*'中,我试图删除else,但它不起作用,因为在ternary operator中,如果之后需要使用else,也尝试了else pass,但它给了我一个错误。

编辑

我可以在查询集之外使用if,但使用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

创建一个带过滤参数的dict怎么样:

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

最新更新