How to select all objects that are not referenced in a many-to-many relationship
I have several Django models set up like this:
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)
In one part of my code, I need to get all section objects where the group field is empty, I can express it using raw SQL, but I would really like to use ORM code if possible. One way to write a query in SQL:
select * from section where id not in (select section_id from section_groups);
Can this requirement be expressed in an ORM query?
+2
source to share
2 answers
Although the SQL generated is slightly different from the sample you are hoping for:
Section.objects.filter(groups__isnull=True)
will do the job.
This generates the following (formatting added)
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
+4
source to share