Can I have a field name with spaces in Django Rest Framework?

Viewed 937

Is there a way to remap the names of Django Rest Framewok SerializerFields to strings that contain spaces?

I have the following sort of code:

models.py:

class Author(models.Model):
    author_name = models.CharField()

serialisers.py:

class AuthorSerializer(serializers.ModelSerializer):
  class Meta:
    model = Author
    fields = ["author_name"]

This will return JSON like:

{ "author_name": "William Shakespeare" }

But I want it to return JSON like:

{ "The Author": "William Shakespare" }

I know that I can use a different name for a serializer field using the source kwarg, but that still requires a valid python name. I'm specifically wondering if I can use a name with spaces in it.

Thanks.

1 Answers

You can override to_representation() method in your serializer class. Something like this:

class AuthorSerializer(serializers.ModelSerializer):
  class Meta:
    model = Author
    fields = ["author_name"]

  def to_representation(self, obj):
    primitive_repr = super(AuthorSerializer, self).to_representation(obj)
    primitive_repr['The Author'] = primitive_repr['author_name']
    return primitive_repr
Related