Django: select all A objects that are involved in m2m relationships with any B objects (via B.m2mfield)
-
28-06-2021 - |
Question
I have a following model:
class People(models.Model):
name=models.CharField
class Recordings(models.Model):
title=models.CharField
performers=models.ManyToManyField(People)
I need to get all people who are performers, i. e. people who are in performers list of at least one recording.
SQL would be like this:
SELECT * FROM people WHERE id IN (SELECT DISTINCT people_id FROM recordings_people)
or
SELECT DISTINCT * FROM recordings_people JOIN people ON recordings_people.people_id=people.id
How can I do the same with Django ORM in an elegant way?
Solution
As easy as 1,2,3 with exclude:
People.objects.exclude(recordings=None)
Is that elegant enough ? ;)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow