Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all objects not referenced in a many-to-many relationship

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?

like image 378
artran Avatar asked Oct 21 '25 23:10

artran


1 Answers

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
like image 164
JJ Geewax Avatar answered Oct 27 '25 06:10

JJ Geewax