Reputation: 9610
Lets say I have following models:
class Book(models.Model):
name = models.CharField(max_length=70)
lang = models.CharField(max_length=70)
author = models.FK(Author)
class Author(models.Model):
name = models.CharField(max_length=70)
And I want to write something to get a list of authors with annotated field which shows amount of books in each language. Can't imagine an annotation for it :(, e.g. {'en': 10, 'ru': 1...etc}
e.g. just counts all, Author.objects.annotate(languages=Count(book__lang))
Upvotes: 3
Views: 2638
Reputation: 186
Simple annotation should help you:
Book.objects.values('lang').annotate(lang=Count('author')).order_by('lang')
Upvotes: 4