I am stuck into this obviously basic issue, it feels I am missing something obvious to make this work properly.
My db model is:
class Review(models.Model):
SCORE_CHOICES = [(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5')]
user = models.ForeignKey(get_user_model(), related_name="reviews_by_user", on_delete=models.CASCADE)
recipe = models.ForeignKey(Recipe, related_name="reviews_by_recipe", on_delete=models.CASCADE)
score = models.IntegerField(choices=SCORE_CHOICES)
date_created = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.user} rated {self.recipe} with {self.score}"
class Meta:
ordering = ['-date_created']
I am trying to group by recipe counting avg review score. This approach feels to work fine but it doesn't:
Review.objects.values('recipe').annotate(Avg('score'))
as result i get:
<QuerySet [{'recipe': 1, 'score__avg': 5.0}, {'recipe': 1, 'score__avg': 5.0}, {'recipe': 2, 'score__avg': 4.0}, {'recipe': 2, 'score__avg': 3.0}, {'recipe': 5, 'score__avg': 3.0}, {'recipe': 5, 'score__avg': 2.0}]>
Which is absolutely weird for me. It should group recipes but instead, it counts avg for each row. I've gone through the Django Aggregation documentation but can't find any restrictions or special clauses that could help to understand what I am missing.
Please let me know if someone has an idea of what's going on.