Django获取对象的对象

时间:2018-05-15 15:59:42

标签: django python-3.x

我有3个型号:

class Project(models.Model):
   ...

class Group(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE,
                                related_name="groups")

class Word(models.Model):  
    group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True,
                              related_name="words")

我想获得项目中的所有单词。我该怎么做?

1 个答案:

答案 0 :(得分:4)

您可以使用跨多个关系的查找:

project = Project.objects.get(...)

project_words = Word.objects.filter(group__project=project)

Django文档参考:https://docs.djangoproject.com/en/2.0/topics/db/queries/#lookups-that-span-relationships