Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMirko Xiang Zhao
17,787 PointsDjango ORM Avg aggregation
I am stuck with more challenge, just missing this one to complete the course and get a shiny new badge. Thanks for the help!
from django.db.models import Avg
from . import models
def current_average():
reviews = models.Review.objects.annotate(
average = Avg('rating')
)
average = reviews.aggregate(average=Avg('average'))
2 Answers
Chris Freeman
Treehouse Moderator 68,454 PointsYou are very close. Two errors:
- Your current code does not return the
average
result, and - reusing
average
as the annotation and aggregate appears to interfere with the results
def current_average():
reviews = models.Review.objects.annotate(
r_average = Avg('rating') # <-- changed to 'r_average'
)
average = reviews.aggregate(average=Avg('r_average')) # <-- changed to 'r_average'
return average # <-- add return statement
While this passes, it is adding an unnecessary step by creating the annotation first. Since each review has but one rating
, the average or "r_average" will be the same value as the rating
. You can skip the annotation and go directly to the aggregation:
def current_average():
average = models.Review.objects.aggregate(average=Avg('rating'))
return average
Arindam Roychowdhury
3,244 Pointsdef current_average():
reviews = models.Review.objects.all()
average = reviews.aggregate(average=Avg('rating'))
return average