[Answered ]-Get all item from a related Models in Django

1👍

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() 
👤binpy

1👍

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

Leave a comment