Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 77 ยท REST APIs

DRF Serializers in Depth

Learn Django REST Framework serializers properly: Serializer vs ModelSerializer vs HyperlinkedModelSerializer, field options, nesting, method fields and validation, all run live.

The DRF overview showed a serializer as a small, hand-built stand-in. In this lesson you use the real Django REST Framework (it is installed into the in-browser Python with micropip), so every output below comes from the actual library. Serializers are the part of DRF you will touch most often, and almost every API bug you meet later (missing fields, wrong nesting, "this field is required") is a serializer question.

A serializer has two directions. Going out, it turns a model instance or queryset into plain Python data (serializer.data). Coming in, it takes untrusted data, validates it (is_valid()), and either exposes validated_data or errors. If you have used Django forms, you already know the shape: declared fields, a validation pass, and a save() that creates or updates something.

Three kinds of serializer

DRF gives you three base classes, from most manual to most automatic:

Class Fields come from Relationships are written as
Serializer Fields you declare by hand Whatever field you pick
ModelSerializer The model, generated for you Primary keys by default
HyperlinkedModelSerializer The model, generated for you URLs of the related objects

Serializer works with any object, not only models. ModelSerializer is what you will use most of the time: it inspects the model, builds matching fields with the same validation (a CharField(max_length=100) becomes a serializer CharField(max_length=100)), and supplies working create() and update() methods. HyperlinkedModelSerializer is the same, but it emits url instead of id and writes relations as links, which suits APIs that follow the "hypermedia" style.

The first example uses a model pair, prints what ModelSerializer generated (the repr is a great debugging tool), and then adds field options.

Python ModelSerializer and field options

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.

Read the repr first. id is read-only because it is the primary key, author became a PrimaryKeyRelatedField that checks the object exists (see the "does not exist" error), and the model's max_length and PositiveIntegerField rules were carried over for free. The extra_kwargs option lets you tweak a generated field without declaring it again.

The field options you will use constantly

Option Meaning
read_only=True Included in output, ignored on input (ids, timestamps, computed values)
write_only=True Accepted on input, never shown (passwords, internal notes)
required=False The key may be missing from input
default=value Used when the key is missing (implies required=False)
allow_null=True null is a valid input value
source="a.b" Read the value from another attribute or path, for example author.name
validators=[...] Extra validators such as UniqueValidator

In Meta, use fields = "__all__" only for throwaway code. An explicit list protects you from accidentally publishing a new column (such as internal_note) the day someone adds it to the model.

write_only=True hides a field from output. It does not make the field safe to accept: validate it like any other input.

Nested serializers and computed fields

A foreign key is output as a bare number by default. To embed the whole related object, declare a serializer as a field. To add a value that is not stored anywhere, use SerializerMethodField, which calls get_<name>() for each object.

Python
# read-only
class AuthorSerializer(serializers.ModelSerializer):
    books = BookSummarySerializer(many=True, read_only=True)   # nested, read-only
    book_count = serializers.SerializerMethodField()           # computed

    class Meta:
        model = Author
        fields = ["id", "name", "books", "book_count"]

    def get_book_count(self, obj):
        return obj.books.count()

Nested serializers are read-only by default in practice: DRF refuses to guess how to save a nested object, and serializer.save() raises an assertion unless you write create() yourself (or mark the nested field read_only=True). The next example does both: a nested read, and an explicit create() that saves an author together with its books inside one transaction.

Python Nested serializers, source and method fields

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.

Look at the error output for the nested payload: the errors are keyed by the position of the failing item. Index 0 is missing because that book was valid, and index 1 shows both the missing title and the invalid pages. Because validation failed, create() never ran, so only the first author exists.

If you only need to show the related name, prefer a flat field over nesting: author_name = serializers.CharField(source="author.name", read_only=True).

Validation: field, object and reusable

DRF has three levels of validation, and they run in this order:

  1. Field validation: the field's own type and options, then any validate_<field_name>(self, value) method.
  2. Object validation: validate(self, attrs), for rules that involve several fields.
  3. Validators attached to the serializer or Meta (for example UniqueTogetherValidator).
Python
# read-only
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ["title", "pages", "min_age", "max_age"]

    def validate_title(self, value):
        if value.isupper():
            raise serializers.ValidationError("Please do not shout.")
        return value.strip()

    def validate(self, attrs):
        if attrs["min_age"] > attrs["max_age"]:
            raise serializers.ValidationError("min_age cannot exceed max_age.")
        return attrs

Errors raised inside validate() appear under the key non_field_errors. To attach an error to a specific field, raise ValidationError({"max_age": "..."}) instead. When a serializer instance is used for an update, self.instance is the existing object, which lets you write rules such as "the status may not go backwards".

Container and hidden fields

Besides the scalar fields, DRF has fields that hold other values.

  • ListField(child=...) accepts a JSON array and validates every element with the child field. min_length, max_length and allow_empty control the size of the list. Errors for one element are reported by its position.
  • DictField(child=...) accepts a JSON object with arbitrary string keys and validates each value with child. Use JSONField instead when the shape is completely free.
  • HiddenField(default=...) is never read from the request and never shown in the output; it only injects a value into validated_data. It is the safe way to stamp something the client must not control, for example the current user (HiddenField(default=serializers.CurrentUserDefault())) or an IP address taken from the request.
  • BooleanField(allow_null=True) is the replacement for the removed NullBooleanField: true, false and null are all valid.
Python ListField, DictField and HiddenField

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 list error is keyed by the index of the bad element (1 above), the dictionary error by the bad key (k), and the hidden source value reached validated_data although it is absent from the output. CurrentUserDefault reads request.user from the serializer's context, so pass context={"request": request} (generic views do this for you).

HyperlinkedModelSerializer

HyperlinkedModelSerializer replaces id with url, and writes relations as URLs. It must know how to build those URLs, so it needs the current request in its context and URL names of the form <model>-detail. DRF's views pass the context for you; here is the read-only shape:

Python
# read-only
class BookSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = ["url", "title", "author"]

# {"url": "http://api.example.com/books/1/", "title": "...", "author": "http://api.example.com/authors/3/"}

Without the request in the context you get an AssertionError, which is the usual first surprise. Most JSON APIs that are consumed by a single-page app or a mobile app skip hyperlinks and use plain ids, because clients can build URLs themselves.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which serializer option makes a field appear in responses but be ignored in request data?

    read_only fields are used for output only (ids, computed values). write_only is the opposite: accepted on input and never shown, such as a password.
  2. 2. What does serializer.save() do on a ModelSerializer when the nested serializer field is not read_only?

    DRF will not guess how to save nested data. Either mark the nested field read_only=True or write create()/update() yourself.
  3. 3. Where does an error raised with a plain ValidationError('message') inside validate() appear in serializer.errors?

    Object-level errors are grouped under non_field_errors. Raise ValidationError({'field': 'message'}) to attach the error to a specific field.
  4. 4. Why prefer an explicit fields list over fields = 'all' on a public API?

    With all, adding a sensitive column to the model instantly publishes it. An explicit list makes every public field a deliberate decision.

Summary

  • A serializer converts objects to plain data (.data) and validates input (is_valid(), .errors, .validated_data).
  • ModelSerializer generates fields and create()/update() from the model; HyperlinkedModelSerializer writes URLs and needs request in the context.
  • Use read_only, write_only, required, default, source and extra_kwargs to shape fields.
  • Nested serializers read easily but need a custom create()/update() to write; SerializerMethodField adds computed output.
  • Validation runs per field (validate_<field>), then per object (validate()), then validators.

Next: DRF ViewSets, Routers and Generic Views.