Serializing course contents
You need to serialize course contents. The Content model includes a generic foreign key that allows you to associate objects of different content models. Yet, you added a common render() method for all content models in the previous chapter. You can use this method to provide rendered content to your API.
Edit the api/serializers.py file of the courses application and add the following code to it:
from courses.models import Content, Course, Module, Subject
class ItemRelatedField(serializers.RelatedField):
def to_representation(self, value):
return value.render()
class ContentSerializer(serializers.ModelSerializer):
item = ItemRelatedField(read_only=True)
class Meta:
model = Content
fields = ['order', 'item']
In this code, you define a custom field by subclassing the RelatedField serializer field provided by DRF and overriding the to_representation() method. You define the ContentSerializer...