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

发布于 2025-02-07 04:42:24 字数 363 浏览 0 评论 0原文

这应该很简单,因为纯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;

如何正确使用ORM获得此结果?

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:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光清浅 2025-02-14 04:42:24

您可以查询:

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')
)

group由此QuerySet产生的对象将具有额外的属性.username带有用户名称。尽管这可能会引入很多重复的数据,但由于用户名是nonenull),或使用id = 3 。

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. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文