[英]How can I get all Django groups and optionally get associated user record?
This should be pretty simple since it's very simple with pure SQL. I have the following query which gets exactly what I want in Django:这应该非常简单,因为使用纯 SQL 非常简单。我有以下查询,它在 Django 中得到了我想要的:
SELECT auth_group.id, auth_group.name, auth_user.username
FROM auth_group
LEFT JOIN auth_user_groups
ON auth_group.id = auth_user_groups.group_id
LEFT JOIN auth_user
ON auth_user_groups.user_id = auth_user.id
WHERE auth_user.id = 3
OR auth_user.id IS NULL;
How can I get this result using the ORM properly?如何正确使用 ORM 获得此结果?
You can query with:您可以查询:
from django.contrib.auth.models import Group
from django.db.models import F, Q
Group.objects.filter(
Q(user=None) | Q(user=3)
).annotate(
username=F('user__username')
)
The Group
objects that arise from this queryset will have an extra attribute .username
with the name of the user.从此查询集产生的Group
对象将有一个额外的属性.username
和用户名。 Although this will introduce likely a lot of duplicate data, since the username will be either None
( NULL
) or the username of the user with id=3
.尽管这可能会引入很多重复数据,因为用户名要么是None
( NULL
),要么是id=3
的用户的用户名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.