3

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!

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.