I have a question very similar to How to group by AND aggregate with Django
here is my model:
class Author(models.Models):
name = models.CharField(max_length=9)
class Book(models.Models):
author = models.ForeignKey(Author)
score = models.IntegerField()
here is what I want to do:
select distinct(author__name, AVG(score)
from book
where author__name in ('A, 'B', 'C')
group by author__name order by avg desc;
This is what I tried:
print Book.objects.filter(author__name__in=['A', 'B', 'C'])\
.values_list('author__name', 'score')\
.annotate(avg=Avg('score'))
[('A', 22, 22), ('A', 24, 24), ('B', 50, 50), ('B', 52, 52)]
but I want to see:
[('A', 23), ('B', 52)]
Is there a way to do this properly in the query (not in a post-processing code)?