django - Django 的排除和操作条件
问题描述
我想 AND 并将所有排除查询放在一个排除函数中。
context['users'] = User.objects.exclude(userprofile__user_role__role_title='Super Admin').exclude(userprofile__user_is_deleted = True).exclude(is_superuser=True)
上面我有两个排除而不是我想要一个
context['users'] = User.objects.exclude(userprofile__user_role__role_title='Super Admin', userprofile__user_is_deleted = True, is_superuser=True)
但在我看来它不起作用
解决方案
用逗号分隔所有查询就像 AND,如果你想组合多个 AND/OR 操作,你可以在 Django 中使用 Q 对象。
例如
from django.db.models import Q
context['users'] = User.objects.exclude((Q(userprofile__user_role__role_title='Super Admin') & Q(is_superuser=True)) | Q(userprofile__user_is_deleted = True))
它可能对您不起作用的原因是您使用了错误的查询?可能的原因可能是:
- 匹配“超级管理员”,它可能以小写或其他方式存储?尝试使用
icontains
和使用小写“超级管理员” - 没有用户以“超级管理员”为标题,被删除并且同时是超级用户?尝试将所有对象一个一个查询,看看是否有交集?
让我知道它是否有帮助。
推荐阅读
- amazon-web-services - Waiter ChangeSetCreateComplete failed: Waiter 遇到终端故障状态
- python - 在多个文件中追加多行
- python - 为什么 np.argmax(None) 返回 0 而不会抛出异常?
- c - libcurl 和 LD_PRELOAD
- python - 让聊天机器人在不确定答案时说“我不知道”
- javascript - FizzBuzz 函数没有通过不是数字逻辑
- google-apps-script - 如何修复脚本以仅在 onOpen 函数中在某些工作表上工作?
- ios - GTMAppAuth 抛出错误«无法打开 Safari»
- python - 合并列表中具有相同键的字典
- reactjs - Next.js 滚动条导航栏