Serializers: Django Rest Framework Crash Course in 2022

LegionScript
2 min readMay 5, 2022

--

Code on Github

WATCH: Django Rest Framework Video Tutorials Playlist

LEARN: Free Structured Software Development Courses

Now that we have a basic project set up let’s go step by step through all of the different parts of the Django Rest Framework. First, we will go over serializers. Serializers take querysets and model instances and convert them into native Python data types. We can then take those data types and render them into JSON. If you’ve used Django Forms or Models before, a lot of this will look very similar.

Basic Serializer

We could always define a basic serializer and define all of the fields manually. The documentation has an example of this:

from rest_framework import serializersclass CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()

But in most cases, you will have a model object that you want to serialize. In that case, using one of the built in model serializers will make doing this much easier. Let’s look at an example of those now.

ModelSerializer

A model serializer has most of what we need built in. We just need to define the model and what fields we want. Here is an example:

class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']

In the meta class we set the model first, this will need to either be a built in model or something defined in the models.py file. We have two options for the fields, either put the model fields that we want to serialize in a list like in the example above or we could instead do something like this using __all__:

class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ‘__all__’

This will serialize all of the fields in the model, it is just a shortcut to avoid having to type out all of the fields in the list.

HyperlinkedModelSerializer

Very similarly to the model serializer, we also have the option to use a HyperlinkedModelSerializer. The main difference between the two is the ModelSerializer will have an id field as the primary key, the HyperlinkedModelSerializer will use a url field instead of an id. Depending on what you need, you will want to choose one or the other. But it is set up the same way, here is an example:

class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ['url', 'id', 'account_name', 'users', 'created']

There are many more customizations and options to get whatever it is that you need but we will stop here for this tutorial. Once you understand these concepts the rest of the advanced customizations will just build off of these ideas.

--

--