Member-only story
How To Use DRF Serializers Effectively in Django
Using the source argument, SerializerMethodField, and to_representation

This post assumes a basic familiarity with the Django REST framework.
We will discuss how we can effectively use serializers during read operations. We will look at three powerful features that will help us achieve the desired results with less code.
We will discuss:
- Multiple ways of using the serializer’s
source
argument. - How and when to use
SerializerMethodField
. - How and when to use
to_representation
.
How To Use the Source Keyword Argument
The DRF serializer provides a keyword argument, called source
, which is extremely smart and can help avoid a lot of common patterns.
Let’s write a serializer that can create serialized representations of a User
.
Let’s use this serializer to serialize a user:
In [1]: from accounts.serializers import UserSerializerIn [2]: from django.contrib.auth.models import UserIn [3]: user = User.objects.latest('pk')In [4]: serializer = UserSerializer(user)In [5]: serializer.data
Out[5]: {'username': 'akshar', 'email': 'akshar@agiliq.com', 'first_name': '', 'last_name': ''}
Suppose the front end or mobile app consuming this API wants the key to be user_name
instead of username
in the serialized representation.
We can add a CharField
on the serializer with a source
attribute to achieve this.