Serializer (DRF)

A serializer in Django REST Framework converts model instances and querysets into JSON for responses, and validates and parses incoming JSON into Python for requests. It is DRF's equivalent of a Django Form for APIs.

Django

Serializers are the translation layer of a DRF API. On output they 'serialize' model objects into JSON-ready data; on input they 'deserialize' request JSON, run validation, and produce validated data you can save. They mirror Django's forms but target JSON instead of HTML.

ModelSerializer is the workhorse: like ModelForm, it builds fields from a model automatically. You set Meta.model and Meta.fields, and it generates fields plus create() and update() methods. For non-model data or full control you use the base Serializer and declare fields yourself.

Validation works through is_valid()/validated_data and per-field validate_<field>() or object-level validate() methods. Nested serializers represent relationships, and read_only/write_only fields control direction (e.g. id is read-only, password is write-only).

Syntax

class PostSerializer(serializers.ModelSerializer):
    class Meta: model = Post; fields = "__all__"

Examples

Python

from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ["id", "title", "body", "created"]
        read_only_fields = ["id", "created"]

Learn it in a lesson

See also

Back to the Dictionary