I have a couple of 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 of the Section objects where the groups field is empty, I can express it using raw SQL but I'd really like to use ORM code if possible. One way of writing the query in SQL is:
select * from section where id not in (select section_id from section_groups);
Is it possible to express this requirement in an ORM query?
Although the SQL generated is slightly different from the sample you're hoping:
Section.objects.filter(groups__isnull=True)
would get the job done.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With