Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Use DRF Serializers Effectively in Django

Akshar Raaj
Better Programming
Published in
5 min readJul 23, 2019
Django REST framework serializers

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Akshar Raaj
Akshar Raaj

Written by Akshar Raaj

Engineer | Open Source | Blogger | Speaker. My posts have been read over a million times. https://www.agiliq.com/authors/#Akshar https://bit.ly/2TaRqji

Responses (8)

Write a response