如何在 Django 中创建虚拟过滤器查询(始终匹配的过滤器)和从不匹配的排除查询。原因是因为我的查询是 None 的情况,在这些情况下我想使用虚拟过滤器。这是代码:
MyModel.objects.filter(filterQuery).exclude(excludeQuery)
如果 filterQuery
或 excludeQuery
为 None
,我会收到错误,因此我想在该查询之前添加以下条件:
if filterQuery == None: filterQuery = ???
if excludeQuery == None: excludeQuery = ???
MyModel.objects.filter(filterQuery).exclude(excludeQuery)
最佳答案
您应该仅在需要时过滤/排除,而不是使用空语句,执行以下操作:
found = MyModel.objects.all()
if filterQuery:
found = found.filter(filterQuery)
if excludeQuery:
found = found.exclude(excludeQuery)
关于python - Django 中的虚拟过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31664828/