Giancarlo Ventura
Giancarlo Ventura

Reputation: 857

Get all item from a related Models in Django

I have Two models related:

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

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

I have an instance of the class author. How can I get all articles of the author? Such as:

articles = author.article_set.getAllArticlesFromAuthor()

I know it can be obtained from a query, but I would like to know if exists a short method provided by Django

Upvotes: 1

Views: 1815

Answers (2)

All Іѕ Vаиітy
All Іѕ Vаиітy

Reputation: 26402

You can create a property

class Author(models.Model):
    # model fields

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

so you can use it like

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

Upvotes: 1

binpy
binpy

Reputation: 4194

Simply way to do it, you can also handle it inside model of Author an example:

class Author(models.Model):

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

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

return QuerySet of articles from specific author.

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

Upvotes: 1

Related Questions