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 Annotate

Aidan Taylor-Lynch
Aidan Taylor-Lynch
7,630 Points

how to perform an average with annotation

Im not sure how to annotate the average of ratings to the review class. I can't really describe my question hopefully you can help.

products/views.py
import datetime

from django.db.models import Q, Avg
from django.shortcuts import render, get_object_or_404

from . import models

def product_list(request):
    products = models.Product.objects.all()
    reviews = products.review.annotate(avg_rating=Avg('rating'))
    return render(request, 'products/product_list.html', {'products': products, 'reviews': reviews})

2 Answers

This one stalled me for quite a while myself. You want to make the annotation to the products queryset and not create one for reviews. The Avg class is a little confusing and I'm not sure what the distinct=True does, but it is necessary.

def product_list(request):
    products = models.Product.objects.all().annotate(
        avg_rating=Avg('review__rating', distinct=True)
    )
    return render(request, 'products/product_list.html', {'products': products})

Happy coding!

Aidan Taylor-Lynch
Aidan Taylor-Lynch
7,630 Points

Thanks Jacinator, the only reason this question threw me, was because it said you will use 'review' not 'review_set', prompting me to work on the Review class.