Django 如何选择多对多关系中未引用的所有对象

Django 如何选择多对多关系中未引用的所有对象,django,django-models,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') gr

我有几个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)
在我的代码的一部分中,我需要获得groups字段为空的所有Section对象,我可以使用原始SQL表示它,但如果可能的话,我真的希望使用ORM代码。用SQL编写查询的一种方法是:

select * from section where id not in (select section_id from section_groups);

有可能在ORM查询中表达这个需求吗?

只是一个猜测,但可能是这样

Section.objects.filter(groups__isnull=True)

虽然生成的SQL与您希望的示例略有不同:

Section.objects.filter(groups__isnull=True)
我会把工作做完的

这将生成以下内容(已添加格式)


好吧,我很尴尬!我真不敢相信我错过了。谢谢
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