2017-03-01 50 views
0

我有相关的有两种型号:获得从相关模型的所有项目在Django

class Author(models.Model): 
    ---- 

class Article(models.Model): 
    author = models.ForeignKey(Author) 
    .... 

我有类作者的一个实例。我如何获得作者的所有文章?如:

articles = author.article_set.getAllArticlesFromAuthor() 

我知道它可以从查询得到,但我想知道是否存在由Django的

提供
+2

我不明白你在问什么;那是article_set已经是什么了。只要做'author.article_set.all()'。 –

+0

我阅读了文档,但没有找到它。 https://docs.djangoproject.com/en/1.10/ref/models/relations/ –

回答

1

简单的方式做到这一点,你也可以处理短的方法它内部型号为Author示例:

class Author(models.Model): 

    def get_articles(self): 
     return Article.objects.filter(author__pk=self.pk) 

class Article(models.Model): 
    author = models.ForeignKey(Author) 
    .... 

返回来自特定作者的文章的QuerySet。

Author.objects.get(pk=1).get_articles() 
1

您可以创建一个属性

class Author(models.Model): 
    # model fields 

    @property 
    def articles(self): 
     return self.article_set.all() 

所以你可以使用它像

author = Author.objects.get(name="Author's Name") # get Author 
articles = author.articles       # get articles by author 
相关问题