首页 > 解决方案 > 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)

但在我看来它不起作用

标签: djangodjango-modelsdjango-formsdjango-views

解决方案


用逗号分隔所有查询就像 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))

它可能对您不起作用的原因是您使用了错误的查询?可能的原因可能是:

  1. 匹配“超级管理员”,它可能以小写或其他方式存储?尝试使用icontains和使用小写“超级管理员”
  2. 没有用户以“超级管理员”为标题,被删除并且同时是超级用户?尝试将所有对象一个一个查询,看看是否有交集?

让我知道它是否有帮助。


推荐阅读