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 Basic ORM Usage Ordering

Can you help me with this task.. im lost

We have a view for showing a product, product_detail, but it currently shows the Reviews in the order they were created. I'd rather show them newest-first, though. Can you use order_by to sort them by created_at in descending order?

import datetime

from django.shortcuts import render, get_object_or_404

from . import models

def good_reviews(request):
    reviews = models.Review.objects.filter(rating__gte=3)
    return render(request, 'products/reviews.html', {'reviews': reviews})

def recent_reviews(request):
    six_months_ago = datetime.datetime.today() - datetime.timedelta(days=180)
    reviews = models.Review.objects.exclude(created_at__lt=six_months_ago)
    return render(request, 'products/reviews.html', {'reviews': reviews})

def product_detail(request, pk):
    product = get_object_or_404(models.Product, pk=pk)
    reviews = product.review_set.all()
    return render(request, 'products/product_detail.html', {'product': product, 'reviews': reviews})

1 Answer

18,814 Points

It's better if you give it your best shot, and then post your code for community members to review. Try taking a look at the documentation for order_by.

If you're still stuck, go ahead and post what you've got and we can take a look.