gpt4 book ai didi

python - 获取属于组的用户

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:09 24 4
gpt4 key购买 nike

我正在尝试获取Creator组和Teacher组中用户的查询集。

test.py,我在其中发送要过滤的组数组:

def test_admin_create_authenticated(self):
data = {"data": {"alert_type":"system", "text": "UnitTest"}, "filters":{"groups":['Teacher', 'Creator'], "together": True}}
url = reverse('admin_alerts-list')
response = self.client.post(url, json.dumps(data), content_type="application/json")
self.assertEqual(response.status_code, status.HTTP_200_OK)

views.py:在这里我想创建一个 q_objects 它将按名称过滤组:

if 'groups' in filters:
print(filters['groups'])
try:
for group in filters['groups']:
q_objects.add(Q(groups__name=group), variable)
except:
q_objects.add(Q(groups=filters['groups']), variable)

然后查找这些组中的所有用户:

print(q_objects)
users = User.objects.filter(q_objects)
print(users.query)
print(users)

终端:

['Teacher', 'Creator']
(AND: ('groups__name', 'Teacher'), ('groups__name', 'Creator'))
SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" INNER JOIN "auth_user_groups" ON ("auth_user"."id" = "auth_user_groups"."user_id") INNER JOIN "auth_group" ON ("auth_user_groups"."group_id" = "auth_group"."id") WHERE ("auth_group"."name" = Teacher AND "auth_group"."name" = Creator)
<QuerySet []>

为什么我的 q_objects 不起作用?我有一个用户属于这两个组。

最佳答案

您正在过滤同时属于'Teacher''Creator'组的用户。而这应该是两个(不同的)组。

您应该通过“链接”此处的 .filter(..) 调用来进行过滤:

users = User.objects.all()

for group in filters.get('groups', ()):
<b>users = users.filter(groups__name=group)</b>

在此 for 循环末尾,users 包含属于 过滤器中所有组的 User ['组']

关于python - 获取属于组的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58605050/

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