Model Serializers In Django Rest Framework

Model Serializers In Django Rest Framework

Model serializers in django rest framework are very similar to the django model forms. By using the model serializers we can reduce the effort of writing the more code for serializers. Model serializers are the shortcuts that allow us to automatically create a serializer with fields that associated with the resective model.

Model serializer class is same as normal serializer class with some extra abilities

  • Model serializer class will automatically generate a set of fields for us, based on the model.
  • IModel serializer class will automatically generate validators for the serializer, such as max_length, unique_together validators, etc.
  • Model serializer class includes default implementations of .create() and .update() Creating a django rest framework Model serializer class

For all model serializers we use "ModelSerializer" class as a base class. It provides the common functionality like fields, validators, etc. automatically. Let's see an example for model serializer.

models.py

from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator

class Movie(models.Model):
    title = models.CharField(max_length=100, unique=True)
    rating = models.FloatField(
        validators=[MinValueValidator(0), MaxValueValidator(10)],
    )
    director = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        return self.title

serializers.py

from rest_framework import serializers
from app.models import Movie

class MovieSerializer(serializers.ModelSerializer):
    class Meta:
        model = Movie
        fields = ('id', 'title', 'rating', 'director')
        # exclude = ('rating',)

By default all the fields we have mentioned in the above model serializer class will be mapped to a corresponding serializer fields. In the above serializer we have added all the field names in the meta class "fields" attribute. we can also do this like fields = '__all__' . If can also specify the fields that we required instead of all fields. We also have the another attribute exclude which will allow us to add all fields to the serializer except one or two fields.

Working with django rest framework model serializers

Let's play with the above serializer that we have created on django shell.

django shell - data serialization

from app.models import Movie
from app.serializer import MovieSerializer
instance = Movie.objects.create(title='Bahubali', rating=8.6, director='Rajamouli')
serializer = MovieSerializer(instance)
print(serializer.data)
# output: {'id': 2, 'title': 'Bahubali', 'rating': 8.6, 'director': 'Rajamouli'}

In the above code we have created the movie model object and serialized it using model serializer

django shell - data validation with serializer

from app.models import Movie
from app.serializer import MovieSerializer
# validate the serilizer data
data = {'title': '', 'rating': 10, 'director': 'James Cameron'}
serializer = MovieSerializer(data=data)
print(serializer.is_valid())
# output: False
print(serializer.errors)
# output: {'title': ['This field is required.']}
data = {'title': 'Avatar', 'rating': 10, 'director': 'James Cameron'}
serializer = MovieSerializer(data=data)
# validate the serilizer data
print(serializer.is_valid())
# output: True

In the above code we have first given the invalid data to the model serializer and the we validated the correctness of the data using is_valid serializer method and then we have printed the errors using the serializer attribute errors. In order to use the attribute errors first we need to call method is_valid otherwise it will raise errors.

django shell - save valid data into database using model serializer

from app.models import Movie
from app.serializer import MovieSerializer
data = {'title': 'Avatar', 'rating': 9, 'director': 'James Cameron'}
serializer = MovieSerializer(data=data)
serializer.is_valid()
# output: True
new_obj = serializer.save()
print(new_obj.id, new_obj.title)
# output: 3 Avatar

In the above code we have given valid data to the serializer and then we have called the is_valid method after that we saved the data to database using the serializer method save. Before calling the method save first we should call is_valid method otherwise it will raises the errors.

django shell - update data in the database using model serializer

from app.models import Movie
from app.serializer import MovieSerializer
data = {'title': 'Avatar', 'rating': 10}
instance = Movie.objects.get(id=3)
serializer = MovieSerializer(instance, data=data)
serializer.is_valid()
instance = serializer.save()
print(instance.rating)
# output: 10

In the above code we have given rating as 10 previously it's value is 9. In the above while initializing the serializer we have provided instance and data to the serializer because when we save the serializer it will updated the given data in the given instance otherwise it will create a new object.

References:
https://www.django-rest-framework.org/api-guide/serializers/