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

5👍

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

2👍

Just a guess, but perhapse

Section.objects.filter(groups__isnull=True)

Leave a comment