如何添加“和quot”条款到Django Orm中的外部连接?

发布于 2025-02-11 12:07:12 字数 583 浏览 0 评论 0原文

假设我有两个表格,auth_group和auth_user_group。他们有一个简单的关系,其中auth_user_group具有一个group_id字段,该字段指向auth_group中的ID字段。假设我们在RAW SQL:编辑中编写了

select *
from auth_group ag
left join auth_user_groups aug
  on ag.id = aug.group_id
  and aug.user_id is null;

查询

select *
from auth_group ag
left join auth_user_groups aug
  on ag.id = aug.group_id
  and aug.user_id = 1;

此 匹配记录以及在不存在的地方将返回null

我该如何在django orm中执行此操作?

更多信息。你为什么要这么做?简单的。我想列出用户可能拥有的所有可能的组,我还想列出他们当前拥有的组。当然,我可以使用两个单独的查询来执行此操作,但是当我可以使用一个简单的查询进行操作时,这效率低下。

Lets say I have two tables, auth_group and auth_user_group. They have a simple relationship where auth_user_group has a group_id field which points to the id field in auth_group. Let's say we wrote this query in raw sql:

select *
from auth_group ag
left join auth_user_groups aug
  on ag.id = aug.group_id
  and aug.user_id is null;

Edit...

The question would be the same if this were the query:

select *
from auth_group ag
left join auth_user_groups aug
  on ag.id = aug.group_id
  and aug.user_id = 1;

My goal here is to get every record from the auth_group table and where there is a matching auth_user_groups record it would return that matching record and where it doesn't exist it would return null

How would I do this in Django ORM?

Further info. Why would I want to do this you ask? Simple. I would like to list all of the possible groups that a user could have and I also want to list which ones they currently have. Sure, I could do this with two separate queries but that is inefficient when I could just do it with one simple query.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文