具有父子M2M关系的django对象查询反向

时间:2019-01-24 15:29:13

标签: django django-models django-queryset

在具有这种对象关系类型的三个模型(对象)的情况下:

# Team = parent, a group or collection of people
class Team(models.Model):
      name = models.CharField(max_length=100, unique=True) 
      ...

# Person = an individual person who belongs to a team
class Person(models.Model):
     # relationships
     team = models.ForeignKey('Team', on_delete=models.CASCADE, related_name='people')
     projects = SortedManyToManyField('Project', related_name='people')


 # Project = each Person can have zero, one, or multiple Projects
 # multiple different teams can work on same Project
 class Project(TimeStampedModel):
       TYPES = Choices( ... )

我知道我可以这样查询“团队中有项目的人”:

user_teams = Team.objects.filter(user=request.user, ...)
people_with_projects = Person.objects.filter(team__in=user_teams, projects=True)

我将如何逆转这种关系以获得“ Foo Team团队成员正在从事的项目列表”的查询集? (即特定团队的项目)。

谢谢

2 个答案:

答案 0 :(得分:0)

类似这样的东西:

#first we get the specific team
team = Team.objects.get(name='Foo',...)
#then enumerate the persons in the team
persons = Person.objects.filter(team=team)
#finally make an array of the projects by person:
projects = []
for person in persons:
    resObj = {}
    resObj['person'] = person.name
    resObj['projects'] = person.projects
    projects.append(resObj)

我认为应该这样做,但不是100%肯定。

答案 1 :(得分:0)

如果我了解您要正确执行的操作,则可以这样做:

team_foo = Team.objects.get(name="Foo")
projects = Project.objects.filter(people__team=team_foo).distinct()

或者只是:

projects = Project.objects.filter(people__team__name="Foo").distinct()

这应该为您提供Foo团队中某人正在从事的所有项目。