开发者

Exclude on a many-to-many relationship through a third table

开发者 https://www.devze.com 2022-12-11 01:58 出处:网络
I have a problem making \"exclude\" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the

I have a problem making "exclude" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the flags "is_green, is_yellow, is_red", like:

class Project(models.Model):
    ...

class Person(models.Model):
    projects = models.ManyT开发者_运维知识库oManyField(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 returning all persons, excluding those which do have the flag "is_red" in a specific project. But the following

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

excludes everyone who is registered at project p but has status=red for any project he is registered. Is there a way to tie the second condition to the first?

My approach was to filter on the Status table directly, which works of course. But then I do have a list of "Status" objects instead of "Person" objects.


Maybe this? (untested)

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


If you have a list of Status objects called 'objects', you can use

[s.person for s in objects]

to make it into a list of the corresponding Persons.

0

精彩评论

暂无评论...
验证码 换一张
取 消