Django Rest Framework - Changing Field Names with Source
Imagine I asked you to build an API endpoint with name
and id
fields that looked like the following.
{
"name": "William Vincent",
"id": "v1.0-2018"
}
Do you see the issue? Using id
is a problem since Django sets id
to the primary key of a database entry by default, yet we need to output id
representing a different value somehow. The answer is to use the source argument in Django Rest Framework’s serializer class.
Here’s what the models.py
and serializers.py
files would look like.
# models.py
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
person_id = models.CharField(max_length=100)
# serializers.py
from rest_framework import serializers
from . import models
class PersonSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='person_id')
class Meta:
model = models.Person
fields = ('name', 'id',)
So the next time you need to override the outputted field name on a model, think first of your serializer and then of source.
Next Steps
Want to learn more about Django APIs? I’ve written an entire book on the subject called Django for APIs. The first two chapters are available to read for free.