Reputation: 945
I have a model of the sort:
class Publisher(models.Model):
...
class Author(models.Model):
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
class Article(models.Model):
author= models.ForeignKey(Author, on_delete=models.CASCADE)
Now I'm trying to get all the articles from a given publisher 'pub'. I've tried doing the following:
pub.article_set()
pub.authot_set().article_set()
As well as other failed tentatives. So how can I retrieve a Queryset of all articles of a given publisher without hitting the database too many times? Whats the most efficient way?
Thanks in advance!
Upvotes: 3
Views: 1723
Reputation: 2819
The most efficient way to reduce number of database queries will be to filter on the queryset of Articles.
# pub is the instance of Publisher
articles = Article.objects.filter(author__publisher=pub)
Upvotes: 5