Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Serializers

Serializer Validation

Validate API input in DRF with field options, reusable validators, validate_<field> methods, object-level validate() and UniqueTogetherValidator, with examples.

Validation is where an API earns trust. DRF checks input in layers, from cheap per-field checks to rules that compare several fields, and every failure ends up in serializer.errors in a predictable shape. Knowing the order of the layers tells you where each rule belongs.

This lesson goes through all four hooks: field arguments, validator functions, validate_<field_name>() and validate(), then adds UniqueTogetherValidator and a few cautions about validating on update.

The order of checks

When you call is_valid(), DRF does this:

  1. For each field: parse the raw value (type conversion), apply the field's own constraints (max_length, min_value, choices), then run its validators.
  2. For each field, run the serializer's validate_<field_name>(value) method if it exists.
  3. Run the serializer-level validators (Meta.validators).
  4. Run validate(attrs) with the combined dictionary.

Errors from steps 1 and 2 are collected per field, so one request reports every bad field at once. If any field fails, the object-level steps (3 and 4) are skipped, so validate() can trust that its fields are individually valid.

Four layers of validation

Field rules type, max_length, choices
Validators reusable functions
validate_field one field, custom rule
validate() rules across fields

Cheap checks first, cross-field checks last.

1 / 2

Field-level validation

Python Field validators and validate methods

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.

Notice three things. validate_username returned a lower-cased string, and that is what ended up in validated_data. The bad username reports only the validator function's message: DRF runs validate_username only when the field's own checks and validators have all passed. And the age and email errors appear in the same response, so the client can fix everything in one round trip.

A validator function is a plain callable that raises ValidationError. It is the right tool for a rule you want to reuse across serializers or on model fields. A validate_<field_name> method is right for a rule that is specific to one serializer or needs self.context (for example self.context["request"].user).

Object-level validation with validate()

Rules that compare fields cannot live on a single field. Use validate(self, attrs), which receives all validated values and must return them (possibly changed).

Python validate() compares 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.

Raising ValidationError("text") from validate() produces {"non_field_errors": ["text"]}. Raising it with a dict attaches the message to a specific field, which clients often prefer because they can highlight the right input. The last call shows that a broken date stops validate() from running, so attrs["check_out"] is always a real date inside it.

Unique together and other serializer validators

ModelSerializer adds UniqueTogetherValidator itself when a model has unique_together or UniqueConstraint. For plain serializers, add it by hand through Meta.validators:

Python UniqueTogetherValidator

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.

UniqueTogetherValidator makes both fields required, because it cannot check uniqueness with a half-filled pair. For "a date may appear once per user" there is UniqueForDateValidator, and you can write your own serializer-level validator as any callable taking the attrs dictionary.

Validating on update

On a partial update (PATCH, partial=True) the attrs in validate() only contain the fields that were sent. Code like attrs["check_out"] then raises KeyError. Read missing values from the instance:

Python
def validate(self, attrs):
    check_in = attrs.get("check_in", getattr(self.instance, "check_in", None))
    check_out = attrs.get("check_out", getattr(self.instance, "check_out", None))
    if check_in and check_out and check_out <= check_in:
        raise serializers.ValidationError("check_out must be after check_in.")
    return attrs

Also remember that a uniqueness check must exclude the object being updated. UniqueValidator and UniqueTogetherValidator do that for you; a hand-written query needs .exclude(pk=self.instance.pk).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method receives the dictionary of all validated fields?

    validate(attrs) is the object-level hook for rules that involve several fields.
  2. 2. What does raising serializers.ValidationError('text') in validate() produce?

    A plain message becomes non_field_errors; pass a dict to attach the message to a particular field.
  3. 3. A field fails its max_length check. Does validate() still run?

    validate() runs only when all individual fields are valid, so it can rely on clean values.
  4. 4. Why can validate() hit a KeyError on a PATCH request?

    With partial=True the attrs dictionary contains just the submitted fields; fall back to the instance for the rest.
  5. 5. Which tool fits a rule that must be reused by several serializers?

    A validator is a plain callable that can be passed to any field's validators list.

Summary

  • DRF validates in layers: field rules and validators, validate_<field>, serializer validators, then validate(attrs).
  • All field errors are reported together; object-level checks only run when every field passed.
  • Return a value from validate_<field> or validate to transform it; raise ValidationError to reject it.
  • Use a dict in ValidationError to attach an error to a field from validate().
  • On partial updates, read missing values from self.instance.

Next: Nested Serializers