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 Relations

Only display review id in courses list instead of review object

In my courses list, where I have added reviews in CourseSerializer but only review id display in course's reviews field instead of complete review object. As:

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        reviews = serializers.HyperlinkedRelatedField(
                    many=True,
                    read_only=True,
                    view_name='apiv2:review_detail',
        )
        fields = (
            'id',
            'title',
            'url',
            'reviews',
        )
        model = models.Course

Result:

[
    {
        "id": 1,
        "title": "Python Basics",
        "url": "https://teamtreehouse.com/library/python-basics",
        "reviews": [
            1,
            2
        ]
    },
    {
        "id": 2,
        "title": "Python Collections",
        "url": "https://teamtreehouse.com/library/python-collections",
        "reviews": []
    },
    {
        "id": 3,
        "title": "Object-Oriented Python",
        "url": "https://teamtreehouse.com/library/object-oriented-python",
        "reviews": []
    }
]

Abdul, try to move the courses variable from CourseSerializer.Meta class to CourseSerializer class.

class CourseSerializer(serializers.ModelSerializer):
    reviews = serializers.HyperlinkedRelatedField(
                many=True,
                read_only=True,
                view_name='apiv2:review_detail',
    )

    class Meta:
        fields = (
            'id',
            'title',
            'url',
            'reviews',
        )
        model = models.Course

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Abdul,

You have two issues. First, you have the reviews attribute defined inside Meta, it should be outside Meta but in CourseSerializer. Because reviews is defined in the wrong place, fields isn't finding your attribute, and instead is finding the reviews related name on the Course model. This is why you're still getting the right results (just not the desired format) in your API.

Second, you have a typo in the view_name kwarg. It should be "apiv2:review-detail" not "apiv2:review_detail".

Cheers

Alex