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 trial

Python Django ORM Total Control Aggregate

Mirko Xiang Zhao
Mirko Xiang Zhao
17,787 Points

Django 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!

products/utils.py
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
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

You 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
Arindam Roychowdhury
3,244 Points
def current_average():
    reviews = models.Review.objects.all()
    average = reviews.aggregate(average=Avg('rating'))
    return average