Exclude many-to-many relationships through the third table

I have a problem doing โ€œexcludeโ€ queries in tables that have many-to-many relationships across the third table. I have a table with projects, a table with people and a relationship table with the flags "is_green, is_yellow, is_red", for example:

class Project(models.Model):
    ...

class Person(models.Model):
    projects = models.ManyToManyField(Project, through='Status')

class Status(models.Model):
    person = models.ForeignKey(Person)
    project = models.ForeignKey(Project)
    is_green = models.BooleanField()
    ...

Now I want to make a query that returns all persons, except those who have the "is_red" flag in a particular project. But the following

Person.objects.exclude(project=p, status__is_red=True)

excludes everyone who is registered in project p, but has the status = red for any project that he registered. Is there a way to associate the second condition with the first?

, , , . "" "".

+3
2

, ? ()

Person.objects.exclude(id__in=Person.objects.filter(project=p, status__is_red=True).values(id))
+4

, ,

[s.person for s in objects]

.

0

Source: https://habr.com/ru/post/1722723/


All Articles