art*_*ran 3 django django-models
我有几个 Django 模型是这样设置的:
class Group(models.model):
name = models.CharField(max_length=50, unique=True)
class Section(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(help_text='Auto generated')
groups = models.ManyToManyField(Group, blank=True)
Run Code Online (Sandbox Code Playgroud)
在我的代码的一部分中,我需要获取组字段为空的所有 Section 对象,我可以使用原始 SQL 来表达它,但如果可能的话,我真的很想使用 ORM 代码。在 SQL 中编写查询的一种方法是:
select * from section where id not in (select section_id from section_groups);
Run Code Online (Sandbox Code Playgroud)
是否可以在 ORM 查询中表达此要求?
尽管生成的 SQL 与您希望的示例略有不同:
Section.objects.filter(groups__isnull=True)
Run Code Online (Sandbox Code Playgroud)
将完成工作。
这会生成以下内容(添加格式)
SELECT
"app_section"."id",
"app_section"."name",
"app_section"."slug"
FROM "app_section"
LEFT OUTER JOIN "app_section_groups" ON
("app_section"."id" = "app_section_groups"."section_id")
WHERE "app_section_groups"."group_id" IS NULL
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1570 次 |
| 最近记录: |