Creating Serializers and ModelSerializers

Tutorial 2 of 5

1. Introduction

Goal

In this tutorial, you will learn how to create serializers and ModelSerializers in Django REST Framework, which are critical for converting complex data types into Python-native data types that can be easily rendered into JSON or other content types.

Learning Outcomes

By the end of this tutorial, you will:
- Understand the concept of serialization in Django
- Know how to create and use serializers and ModelSerializers
- Be able to convert complex data into Python-native data types

Prerequisites

  • Basic knowledge of Python
  • Familiarity with Django and Django REST Framework

2. Step-by-Step Guide

Concepts

Serializers allow complex data such as querysets and model instances to be converted to Python-native data types that can then be easily rendered into JSON, XML, or other content types. ModelSerializers are a shortcut for creating serializers that deal with model instances.

Examples and Best Practices

Let's take an example of a Student model and see how to create a serializer and ModelSerializer for it.

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    school = models.CharField(max_length=100)

To create a serializer for the Student model, you can do the following:

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    age = serializers.IntegerField()
    school = serializers.CharField(max_length=100)

    def create(self, validated_data):
        return Student.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.age = validated_data.get('age', instance.age)
        instance.school = validated_data.get('school', instance.school)
        instance.save()
        return instance

To create a ModelSerializer for the Student model, you can do this:

from rest_framework import serializers
from .models import Student

class StudentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['name', 'age', 'school']

3. Code Examples

Consider the Student model we have. Let's create a serializer and ModelSerializer for it.

Serializer Example

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    age = serializers.IntegerField()
    school = serializers.CharField(max_length=100)

    def create(self, validated_data):
        # This method will be called when you call serializer.save()
        return Student.objects.create(**validated_data)

    def update(self, instance, validated_data):
        # This method will be called when you call serializer.save()
        instance.name = validated_data.get('name', instance.name)
        instance.age = validated_data.get('age', instance.age)
        instance.school = validated_data.get('school', instance.school)
        instance.save()
        return instance

ModelSerializer Example

from rest_framework import serializers
from .models import Student

class StudentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['name', 'age', 'school']
        # 'fields' attribute indicates which fields should be included in the serialized representation

4. Summary

In this tutorial, we covered the basics of creating serializers and ModelSerializers in Django REST Framework. We saw how they are used to convert complex data types into Python-native data types that can be easily rendered into JSON, XML, or other content types.

Next, you can explore how these serializers can be used in your views to handle incoming JSON requests and send JSON responses.

5. Practice Exercises

Exercise 1: Create a Teacher model and write a serializer for it.

Exercise 2: Update the Teacher serializer to a ModelSerializer.

Exercise 3: Add a custom validation method to the Teacher ModelSerializer.

Remember, practice makes perfect. Keep coding!