0

I am currently struggling to figure out how to deal with the following problem:

Imagine I got this two models:

class author(models.Model):
     name = models.CharField(mac_length=50)
     ...

and

class book(models.Model):
     author = models.ForeignKey('author', on_delete=models.CASCADE)
     ...

Now I want to create a view which list all authors with all their book's. This could look something like this:

Joanne K. Rowling:

  • Harry Potter and the Philosopher's Stone
  • ...

J. R. R. Tolkien:

  • The Hobbit
  • ...

Question:
How should the Django Query look like to access the Books in the template? `

authors = authors.objects.all()

This gives me the set for the authors, but not their belonging books. Is there a way to annotate or aggregate Dict's to the Queryset? I feel like this beeing Rookie stuff, but it would still be nice if you could help me out.

1 Answer 1

2

I think you are looking for something like :

authors = authors.objects.all().prefetch_related('book_set')

then access them this way:

for author in authors:
    books = author.book_set.all()
Sign up to request clarification or add additional context in comments.

1 Comment

please add explanation and/or relevant documentation as well.

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.