gpt4 book ai didi

python - Django 中的虚拟过滤器

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:42 25 4
gpt4 key购买 nike

如何在 Django 中创建虚拟过滤器查询(始终匹配的过滤器)和从不匹配的排除查询。原因是因为我的查询是 None 的情况,在这些情况下我想使用虚拟过滤器。这是代码:

MyModel.objects.filter(filterQuery).exclude(excludeQuery)

如果 filterQueryexcludeQueryNone,我会收到错误,因此我想在该查询之前添加以下条件:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com