Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Serializers

Serializer Basics

Learn the DRF Serializer class: declared fields, converting objects to JSON-ready data, validating input, many=True, and writing create() and update().

A serializer is the contract between your internal objects and the outside world. Going out, it converts rich Python objects (model instances, dates, decimals) into simple types that a renderer can write as JSON. Coming in, it takes untrusted dictionaries from request.data, checks every field and hands back clean values or a list of errors.

The base class is serializers.Serializer. You declare fields on it just like you declare fields on a Django form or model. This lesson uses plain Python objects so you can see the serializer by itself; the next lessons add field options and model serializers.

Declaring a serializer

Python
from rest_framework import serializers


class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

Each class attribute is a field. The field decides how to convert a value in both directions (to_representation going out, to_internal_value coming in) and which checks to run.

Objects to data: serialization

Pass an instance as the first argument and read .data.

Python Serializing objects and lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Several things happened. .data is a dictionary-like object holding plain values; the datetime became an ISO 8601 string with a Z for UTC. JSONRenderer turned that data into bytes, which is exactly the last step a Response performs for you. And many=True told the serializer to expect an iterable, so .data is a list.

Attributes are read with getattr, so the serializer does not care whether the object is a model instance, a dataclass, a named tuple or a plain class. Dictionaries work too, because the field falls back to a key lookup.

Data to objects: deserialization and validation

For input, pass data= instead. Nothing is checked until you call is_valid().

Python Validating incoming data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The valid case gives validated_data: a dictionary of Python values (the optional created is absent because the client did not send it). The invalid case collects all problems, one list of messages per field, so you can show them together. The non_field_errors key appears when the whole payload is wrong, such as a list instead of an object. Reading .data too early is blocked with an assertion, because there is nothing safe to show yet.

Call is_valid(raise_exception=True) in views. If validation fails, DRF raises ValidationError and the client gets a 400 response with serializer.errors as the body, so you do not repeat the error-handling code.

Saving: create() and update()

A plain Serializer does not know how to save. You implement create() and update() yourself, and save() decides which one to call: update() when the serializer was given an instance, create() otherwise. The values come from validated_data.

Python Implementing create() and update()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The id field is read_only: it appears in output but is ignored in input, so a client cannot choose its own identifier. The non-partial update printed an empty error dictionary because body is declared required=False, so title alone satisfies a full update; with a required field missing, only partial=True would let it through. Finally, save(body="from the view") shows how a view can inject values the client must not control, such as the current user; the extra keyword arguments are merged into validated_data.

flowchart LR
    A["Serializer(instance)"] -->|".data"| B["plain dict"]
    C["Serializer(data=...)"] -->|"is_valid()"| D["validated_data / errors"]
    D -->|"save()"| E{"instance given?"}
    E -->|yes| F["update()"]
    E -->|no| G["create()"]

The two directions of a serializer: output from objects, input through validation and save.

Useful serializer attributes

Attribute Meaning
serializer.data Output data (after is_valid() + save() for input serializers)
serializer.validated_data Clean input values, only after a successful is_valid()
serializer.errors Dictionary of problems after a failed is_valid()
serializer.instance The object being updated, or the result of save()
serializer.initial_data The raw input
serializer.fields The bound field objects, useful for introspection

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you serialize a list of objects?

    many=True makes the serializer iterate over the input and produce a list.
  2. 2. When must you call is_valid()?

    Input is not checked until is_valid() runs. validated_data, errors and save() depend on it.
  3. 3. What decides between create() and update() when you call save()?

    With an instance, save() calls update(instance, validated_data); otherwise it calls create(validated_data).
  4. 4. What does read_only=True mean on a field?

    Read-only fields such as id are never taken from the client.

Summary

  • A Serializer declares fields; instances go out through .data, input comes in through data= and is_valid().
  • many=True handles lists; partial=True allows missing fields for PATCH-style updates.
  • Errors are a dictionary of field names to message lists, with non_field_errors for whole-payload problems.
  • save() calls your create() or update(); extra keyword arguments flow into validated_data.
  • Use is_valid(raise_exception=True) in views.

Next: Serializer Fields