Given models set up like this:
class Author(models.Model):
name = models.CharField(max_length=255)
class Genre(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
How can I count the number of genres each author has written for? I would ideally like a dictionary of genres and book counts for each author.
[{id: author.id, genres: {genre.id: number_of_books}}]
This can easily be achieved with a query to Author for each genre, however this would result in [number of authors]*[number of genres] queries. I would like to find a more efficient method if possible.