Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Serializers

ModelSerializer: Serializers Built from Models

Use DRF's ModelSerializer to generate fields, validators, create() and update() from a Django model, then tune it with Meta options and extra_kwargs.

Writing a Serializer field by field is clear but repetitive when your model already says what the fields are. ModelSerializer reads a Django model and builds the serializer for you: it picks a field class for every model field, copies max_length, null and blank rules, adds uniqueness validators and gives you working create() and update() methods.

In this lesson you will see what it generates, how to choose and restrict fields, how to pass per-field options and how to peek at the generated code so nothing feels like magic.

The smallest ModelSerializer

Python A ModelSerializer in six lines

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 rules came for free: title is required with a 100-character limit, pages rejects a negative number because the model field is a PositiveIntegerField, price allows at most six digits in total, published is optional because the model allows null and blank, and the second Dune fails because DRF added a UniqueValidator for unique=True. Nothing in BookSerializer states any of that.

Seeing what was generated

repr() of a serializer instance prints the field list that DRF built. It is the best debugging tool for a ModelSerializer.

Python repr() shows the generated 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.

You will see id = IntegerField(label='ID', read_only=True), a CharField with its validators, and so on. When a field behaves strangely, compare this output with what you expected.

Choosing fields: fields, exclude and __all__

Meta option Meaning When to use
fields = [...] Exactly these fields, in this order The recommended default
fields = "__all__" Every model field Quick prototypes only
exclude = [...] Every field except these Short lists of secrets
read_only_fields = [...] Output only Server-set values such as timestamps

Prefer an explicit fields list. With "__all__" or exclude, adding a column to the model silently publishes it through the API, including that internal cost_price or is_staff_note column you added next month.

You can also list names that are not columns: a property or method on the model, a field you declare on the serializer, or a related-object field. They are included in the output like any other.

Per-field options with extra_kwargs

You can tweak generated fields without declaring them by hand:

Python
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username", "email", "password"]
        extra_kwargs = {
            "password": {"write_only": True, "min_length": 8},
            "email": {"required": True},
        }

write_only keeps the password out of every response; required turns a blank-able column into a required input. Use read_only_fields when the only change is read-only, and extra_kwargs for everything else.

Python Meta options in action

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.

Four things to check in the output: the short password and missing email are reported, password never appears in the response data, the client's created value was ignored because the field is read-only, and display (a model property) shows up as a read-only field.

What create() and update() do

ModelSerializer.create() calls Model.objects.create(**validated_data), and update() assigns each validated value to the instance and calls save(). That is right for flat models. It does not handle:

  • Nested writes (a serializer inside another): you must override create(); see Nested Serializers.
  • Many-to-many fields on creation: DRF sets them after the instance is saved, which works for simple primary-key lists.
  • Hashing passwords or other side effects: override the method, as the example above did.

Common mistakes

  • Forgetting fields or exclude. DRF raises an AssertionError; it refuses to guess.
  • Using "__all__" in production code. It couples your public API to your table layout.
  • Putting required=False in extra_kwargs for a non-null column without a default. Validation passes, then the database rejects the insert.
  • Declaring a field on the serializer and also listing it in extra_kwargs. Explicit declarations win and extra_kwargs is ignored for them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ModelSerializer generate from a model?

    It builds serializer fields from the model fields, including validators, and supplies working create() and update() methods.
  2. 2. Why is fields = 'all' risky?

    Every column you add later becomes public without anyone deciding that.
  3. 3. How do you accept a password on input but never return it?

    write_only fields are used for input and left out of the output.
  4. 4. A model has unique=True on a column. What happens in a ModelSerializer for that column?

    ModelSerializer adds UniqueValidator automatically, producing a field error instead of a database exception.

Summary

  • ModelSerializer derives fields, validators, create() and update() from a model.
  • List fields explicitly; use read_only_fields and extra_kwargs for per-field tweaks.
  • Model properties and methods can be listed in fields as read-only output.
  • repr(serializer) shows exactly what was generated.
  • Override create() or update() for nested data, password hashing or other side effects.

Next: Serializer Validation