2👍
✅
If you’re querying all or several authors, I recommend prefetching related fields. This will snatch up all related objects in a single hit to the database, and store the objects in the Queryset.
authors = Author.objects.all().prefetch_related('book_set')
for author in authors:
# accessing related field will not cause a hit to the db,
# because values are cached in Queryset
for book in author.books_set:
print book.genre
If you’re only querying one author, then it’s not such a big deal.
author = Author.objects.get(pk=1)
her_books = author.book_set
for book in her_books:
print book.genre
Edit
I’m having a bit of trouble understanding exactly what you’re going to do. But, if you’re looking for the latest book of each genre, for a given author:
author = Author.objects.get(pk=1)
author_books = author.book_set.order_by('-date') # most recent, first
author_genres = set([b.genre for b in author_books])
for g in author_genres:
print next((b for b in author_books if b.genre==g), None)
Keep in mind that these operations are all on the Queryset, and are not hitting the database each time. This is good, because querying the database is an expensive operation, and most authors have a relatively small list of works, so the Querysets will generally be small.
Source:stackexchange.com