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

Nathan Magyar
Nathan Magyar
11,332 Points

Error: "Didn't find the right average"

Hello, I've tried rewatching the associated video for .aggregate() but seem to be missing something in the function below. Thanks for your help!

The prompt is: We're getting a lot of reviews! That's great! I'm worried, though, that our overall catalog isn't very well-rated. Update the current_average function to return the aggregate average rating for all Reviews. You should give it the key name of "average".

from django.db.models import Avg

from . import models

def current_average():
    reviews = models.Review.objects.all().aggregate(average=Avg("review__rating"))
    return reviews.average

1 Answer

Alex Koumparos
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Nathan,

You've got a couple of minor issues with your code. First, rating is a field on Review, and Review is the model you are applying aggregate to, therefore you don't want to describe rating as "review__rating": this would imply that Review has some field called review which is a relation to an model that has a rating field at the other end. Instead, you can just ask for "rating" directly.

Second, the object you're going to get back is a Python dictionary with just one key: "average" and one value (whatever the average of the ratings is). As such, it doesn't have an attribute called average that you can access using dot syntax, instead just return the dictionary.

Hope that clears everything up for you,



Nathan Magyar
Nathan Magyar
11,332 Points

Hi Alex,

Ah, I see. That helps a lot. Thanks!