获取属于组的用户

时间:2019-10-29 09:56:55

标签: python django django-q

我正在尝试获取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不起作用?我有一个属于这两个组的用户。

1 个答案:

答案 0 :(得分:0)

您正在过滤同时属于 a 组的用户,这些组分别名为'Teacher''Creator'。那应该是两个(不同的)组。

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

users = User.objects.all()

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

在此for循环的结尾,然后users包含属于User中所有组的filters['groups']