python - Django 中的虚拟过滤器

标签 python django django-models django-queryset django-orm

如何在 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/

相关文章:

python - 没有名为 _imagingft 的模块

django:CMS 的递归/树状 URL 映射?

python - 将 % 格式更改为 f 字符串

python - 反转字母表

python - Python 中的 For 循环从短 URL 读取长 URL

Django 1.8 : How can I ensure that of Two Fields in a Model, 至少一个或只有一个必须满足条件?

python - 具有引用同一模型的多个一对多关系的django

python - Django 表单未提交

python - Django Rest 框架 URL 模式

django - 如何在 Django 中的 `extra` 调用提供的计算字段上过滤查询集?