2017-03-01 47 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 
相關問題