I'm using Django 3.0 and I have a serializer using django-rest-framework
. Let's say that for example I have a Forum
object. Each forum
has an owner
that is a user.
In my GET /forums/
endpoint, I'd like to just have the owner_id
. However, in my GET /forums/<forum_id>/
endpoint I'd like to return the entire embedded object.
Is there any way to have one serializer support both of these scenarios? If not, I would hate to have to make two serializers just to support this.
class ForumSerializer(serializers.ModelSerializer, compact=True):
if self.compact is False:
owner = UserSerializer(source='owner', read_only=True)
else:
owner_id = serializers.UUIDField(source='owner_id')
...
How can I achieve this compact thing?
class Meta:
fields = [...]
read_only_fields = ['owner', 'owner_id']