How to make a Django Serializer

Yashod Perera
Nov 10, 2020
Photo by Daniel Dara on Unsplash

How to translate django models or objects into any format. Let’s start.

First you have to install django rest framework to use the serializer as follows.

// Install globally
pip install djangorestframework
// Install using pipenv
pipenv install djangorestframework

Then add the django rest framework to the installed apps in settings.py.

INSTALLED_APPS = [
...
'rest_framework',
]

First let’s make a simple model in models.py

from django.db import modelsclass Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField(max_length=254)
def __str__(self):
return self.name

Then let’s create a serialiser which help us to convert data to a format which can be easily rendered into JSON, XML or other content types. Following code is placed in serializers.py .

from rest_framework import serializers
from .models import Person
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Collection
fields = ['id', 'name', 'age']

In serializer class you can get all the fields by altering fields = '__all__' or you can get all the fields excluding one fields changing fields to exclude = ['email'] .

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor