We need to serialize course contents. The Content model includes a generic foreign key that allows us to associate objects of different content models. Yet, we have added a common render() method for all content models in the previous chapter. We can use this method to provide rendered contents to our API.
Edit the api/serializers.py file of the courses application and add the following code to it:
from ..models import Contentclass 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, we define a custom field ...