Creating nested serializers

We are going to create a serializer for the Course model. Edit the api/serializers.py file of the courses application and add the following code to it:

from ..models import Courseclass CourseSerializer(serializers.ModelSerializer):    class Meta:        model = Course        fields = ['id', 'subject', 'title', 'slug', 'overview',                  'created', 'owner', 'modules']

Let's take a look at how a Course object is serialized. Open the shell, run python manage.py shell, and run the following code:

>>> from rest_framework.renderers import JSONRenderer>>> from courses.models import Course>>> from courses.api.serializers import CourseSerializer>>> course = Course.objects.latest('id')>>> serializer = CourseSerializer(course)>>> JSONRenderer().render(serializer.data) ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.