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 REST Framework Make the REST Framework Work for You Viewsets and Routers

Dmitry Karamin
Dmitry Karamin
10,099 Points

Why does it works this way?

It this decorated function

@detail_route(methods=['get'])
def reviews(self, request, pk=None):
    course = self.get_object()
    serializer = serializers.ReviewSerializer(
        course.reviews.all(), many=True)
    return Response(serializer.data)

i wonder why this line works course.reviews.all()

Course model doesn't have review fields so why it doesn't raise any error?

2 Answers

Jeremy Chen
Jeremy Chen
2,602 Points

@detail_route is deprecated now. Also, this code doesn't work for me.

This is how I do it.

    @action(methods=["get"], detail=True)
    def reviews(self, request, pk=None):
        course = self.get_object()
        reviews = models.Review.objects.filter(course=course)
        serializer = serializers.ReviewSerializer(reviews, many=True)
        return Response(serializer.data)