Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Serializers

Serializer Fields

Tour DRF serializer fields: CharField, IntegerField, ChoiceField, DateField, ListField and more, plus options like required, default, read_only, source and validators.

A serializer is only as good as its fields. Each field class knows one kind of value: how to check it on the way in and how to format it on the way out. DRF ships fields for text, numbers, dates, choices, files and collections, plus a set of options that all fields share. Learning them well means most validation rules in your API are a single keyword argument.

Common field types

Field Input accepted Output
CharField string (max_length, min_length, allow_blank) string
EmailField, URLField, SlugField, UUIDField, IPAddressField validated strings string
IntegerField, FloatField, DecimalField numbers or numeric strings number (Decimal as string by default)
BooleanField true, false, "1", "on", ... true / false
DateTimeField, DateField, TimeField, DurationField ISO 8601 strings ISO 8601 strings
ChoiceField, MultipleChoiceField one of fixed values the value
ListField, DictField, JSONField arrays, objects, any JSON same
FileField, ImageField uploads URL
SerializerMethodField, ReadOnlyField, HiddenField special, see below

A tour in one example

Python Fields convert and validate

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.

Study the conversions: the string "19.5" became Decimal('19.50'), "12" became 12, the date string became a date object, and "maybe" was rejected as a boolean. Notice also that output shows the price as the string "19.50". That is deliberate: JSON numbers are floating point, so DRF protects money from rounding by sending decimals as strings. If you prefer numbers, set COERCE_DECIMAL_TO_STRING = False in REST_FRAMEWORK, or use coerce_to_string=False on one field.

Options shared by all fields

Every field accepts these keyword arguments:

Option Effect
required Whether the key must be present in input (default True)
default Value to use when the key is missing (implies required=False)
allow_null Accept None as a valid value
read_only Output only; ignored in input
write_only Input only; never shown in output (passwords)
source The attribute (or dotted path) to read from the object
label, help_text Documentation text for the browsable API and schema
validators A list of extra validator callables
error_messages Override messages by error code
initial, style Control how the HTML form renders
Python required, default, source, write_only and error_messages

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.

source="email" lets the public name (login_email) differ from the internal attribute. Notice that during validation the data comes back under the source name (email), because validated_data is meant for your model code. source="profile.city" follows an attribute path, which is handy for flattening nested data. The password field is accepted but never appears in output, and the ignored city input proves that read-only fields cannot be written by clients. The custom error_messages replaced DRF's default text for the max_length code.

ChoiceField and its display values

ChoiceField accepts either a list of values or pairs of (value, label). The value is what travels over the wire; the label is documentation. Add allow_blank=True to accept an empty string, and choices may come from a Django TextChoices enum, which keeps the API and the model in step.

Python
class Status(models.TextChoices):
    DRAFT = "draft", "Draft"
    PUBLISHED = "published", "Published"


class PostSerializer(serializers.Serializer):
    status = serializers.ChoiceField(choices=Status.choices, default=Status.DRAFT)

Computed values: SerializerMethodField

When a value does not exist as an attribute, compute it. SerializerMethodField calls get_<field_name>(self, obj) and is always read-only.

Python SerializerMethodField, HiddenField and ReadOnlyField

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.

HiddenField is the safe way to inject a server-side value into validated_data, for example the current user (default=serializers.CurrentUserDefault()) or a timestamp. It never reads client input and never appears in output.

Writing a custom field

When no built-in field matches, subclass Field and implement the two conversion methods. A common example is a field that stores a value one way and shows it another way.

Python A custom field

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which option makes a field appear in output but never be read from input?

    read_only fields are ignored in input. write_only is the opposite: accepted but never shown.
  2. 2. Why does DecimalField output a string by default?

    Strings keep the exact decimal value. You can switch with COERCE_DECIMAL_TO_STRING=False.
  3. 3. What does source="profile.city" do?

    source can be a dotted path, which flattens nested attributes into one field.
  4. 4. How do you add a server-supplied value to validated_data that the client cannot override?

    HiddenField ignores client input and uses its default, and it is never shown in output.
  5. 5. What are the two methods of a custom Field?

    to_representation converts a Python value for output; to_internal_value validates and converts input.

Summary

  • Fields convert and validate: use the most specific one (EmailField, DateField, ChoiceField) before reaching for custom code.
  • Shared options: required, default, allow_null, read_only, write_only, source, validators, error_messages.
  • source renames or flattens attributes; SerializerMethodField computes read-only values; HiddenField injects server values.
  • Decimals are sent as strings to protect precision.
  • A custom field implements to_representation and to_internal_value.

Next: Model Serializers