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.

MichaelKleine
  • 159
  • 1
  • 9

1 Answers1

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