简体   繁体   English

如何获取所有 Django 组并有选择地获取关联的用户记录?

[英]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.

相关问题 Libtorrent:如何获取与会话关联的所有torrent句柄? - Libtorrent: how can I get all torrent handles associated with a session? 如何纠正我的ORM语句以显示未与Django中的用户关联的所有朋友? - How can I correct my ORM statement to show all friends not associated with a user in Django? 在django-taggit中,如何获取与特定用户关联的对象的标签? - In django-taggit, how to get tags for objects that are associated with a specific user? 我如何从给定记录中获取用户ID值 - How can i get the user id value from a given record Python正则表达式组:如何获得所有组? - Python regexp groups: how do I get all groups? 如何在django监护人中获取用户具有特定权限的所有对象? - How can I get all objects a user has specific permissions to in django guardian? 我如何获得被捕团体的位置? - How can I get the position of the captured groups? 如何使用 bitcoinlib 获取与我的公钥关联的所有地址? - How can I get all the addresses associated with my public key with bitcoinlib? 如何在Django中使用不同的用户组重新发布视图 - How can I rediredct the views with different user groups in django Django:获取模板的所有权限,按组分隔 - Django: get all permissions on template separated by groups
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM