rest_framework.serializers

Serializers and ModelSerializers are similar to Forms and ModelForms. Unlike forms, they are not constrained to dealing with HTML output, and form encoded input.

Serialization in REST framework is a two-phase process:

1. Serializers marshal between complex types like model instances, and python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers.

Module Contents

LIST_SERIALIZER_KWARGS = ['read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'allow_empty', 'instance', 'data', 'partial', 'context', 'allow_null']
ALL_FIELDS = __all__
class BaseSerializer(instance=None, data=empty, **kwargs)

Bases:rest_framework.fields.Field

The BaseSerializer class provides a minimal class which may be used for writing custom serializer implementations.

Note that we strongly restrict the ordering of operations/properties that may be used on the serializer in order to enforce correct usage.

In particular, if a data= argument is passed then:

.is_valid() - Available. .initial_data - Available. .validated_data - Only available after calling is_valid() .errors - Only available after calling is_valid() .data - Only available after calling is_valid()

If a data= argument is not passed then:

.is_valid() - Not available. .initial_data - Not available. .validated_data - Not available. .errors - Not available. .data - Available.

data
errors
validated_data
classmethod __new__(cls, *args, **kwargs)
classmethod many_init(cls, *args, **kwargs)

This method implements the creation of a ListSerializer parent class when many=True is used. You can customize it if you need to control which keyword arguments are passed to the parent, and which are passed to the child.

Note that we’re over-cautious in passing most arguments to both parent and child classes in order to try to cover the general case. If you’re overriding this method you’ll probably want something much simpler, eg:

@classmethod def many_init(cls, *args, **kwargs):

kwargs[‘child’] = cls() return CustomListSerializer(*args, **kwargs)
to_internal_value(self, data)
to_representation(self, instance)
update(self, instance, validated_data)
create(self, validated_data)
save(self, **kwargs)
is_valid(self, raise_exception=False)
class SerializerMetaclass

Bases:type

This metaclass sets a dictionary named _declared_fields on the class.

Any instances of Field included as attributes on either the class or on any of its superclasses will be include in the _declared_fields dictionary.

classmethod _get_declared_fields(cls, bases, attrs)
classmethod __new__(cls, name, bases, attrs)
as_serializer_error(exc)
class Serializer

Bases:rest_framework.serializers.BaseSerializer

default_error_messages
fields

A dictionary of {field_name: field_instance}.

data
errors
_writable_fields(self)
_readable_fields(self)
get_fields(self)

Returns a dictionary of {field_name: field_instance}.

get_validators(self)

Returns a list of validator callables.

get_initial(self)
get_value(self, dictionary)
run_validation(self, data=empty)

We override the default run_validation, because the validation performed by validators and the .validate() method should be coerced into an error dictionary with a ‘non_fields_error’ key.

_read_only_defaults(self)
run_validators(self, value)

Add read_only fields with defaults to value before running validators.

to_internal_value(self, data)

Dict of native values <- Dict of primitive datatypes.

to_representation(self, instance)

Object instance -> Dict of primitive datatypes.

validate(self, attrs)
__repr__(self)
__iter__(self)
__getitem__(self, key)
class ListSerializer(*args, **kwargs)

Bases:rest_framework.serializers.BaseSerializer

child
many = True
default_error_messages
data
errors
bind(self, field_name, parent)
get_initial(self)
get_value(self, dictionary)

Given the input dictionary, return the field value.

run_validation(self, data=empty)

We override the default run_validation, because the validation performed by validators and the .validate() method should be coerced into an error dictionary with a ‘non_fields_error’ key.

to_internal_value(self, data)

List of dicts of native values <- List of dicts of primitive datatypes.

to_representation(self, data)

List of object instances -> List of dicts of primitive datatypes.

validate(self, attrs)
update(self, instance, validated_data)
create(self, validated_data)
save(self, **kwargs)

Save and return a list of object instances.

is_valid(self, raise_exception=False)
__repr__(self)
raise_errors_on_nested_writes(method_name, serializer, validated_data)

Give explicit errors when users attempt to pass writable nested data.

If we don’t do this explicitly they’d get a less helpful error when calling .save() on the serializer.

We don’t automatically support these sorts of nested writes because there are too many ambiguities to define a default behavior.

Eg. Suppose we have a UserSerializer with a nested profile. How should we handle the case of an update, where the profile relationship does not exist? Any of the following might be valid:

  • Raise an application error.
  • Silently ignore the nested part of the update.
  • Automatically create a profile instance.
class ModelSerializer

Bases:rest_framework.serializers.Serializer

A ModelSerializer is just a regular Serializer, except that:

  • A set of default fields are automatically populated.
  • A set of default validators are automatically populated.
  • Default .create() and .update() implementations are provided.

The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don’t need to dig into the implementation.

If the ModelSerializer class doesn’t generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a Serializer class.

serializer_field_mapping
serializer_url_field
serializer_choice_field
url_field_name
create(self, validated_data)

We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just:

return ExampleModel.objects.create(**validated_data)

If there are many to many fields present on the instance then they cannot be set until the model is instantiated, in which case the implementation is like so:

example_relationship = validated_data.pop(‘example_relationship’) instance = ExampleModel.objects.create(**validated_data) instance.example_relationship = example_relationship return instance

The default implementation also does not handle nested relationships. If you want to support writable nested relationships you’ll need to write an explicit .create() method.

update(self, instance, validated_data)
get_fields(self)

Return the dict of field names -> field instances that should be used for self.fields when instantiating the serializer.

get_field_names(self, declared_fields, info)

Returns the list of all field names that should be created when instantiating this serializer class. This is based on the default set of fields, but also takes into account the Meta.fields or Meta.exclude options if they have been specified.

get_default_field_names(self, declared_fields, model_info)

Return the default list of field names that will be used if the Meta.fields option is not specified.

build_field(self, field_name, info, model_class, nested_depth)

Return a two tuple of (cls, kwargs) to build a serializer field with.

build_standard_field(self, field_name, model_field)

Create regular model fields.

build_relational_field(self, field_name, relation_info)

Create fields for forward and reverse relationships.

build_nested_field(self, field_name, relation_info, nested_depth)

Create nested fields for forward and reverse relationships.

build_property_field(self, field_name, model_class)

Create a read only field for model methods and properties.

build_url_field(self, field_name, model_class)

Create a field representing the object’s own URL.

build_unknown_field(self, field_name, model_class)

Raise an error on any unknown fields.

include_extra_kwargs(self, kwargs, extra_kwargs)

Include any ‘extra_kwargs’ that have been included for this field, possibly removing any incompatible existing keyword arguments.

get_extra_kwargs(self)

Return a dictionary mapping field names to a dictionary of additional keyword arguments.

get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs)

Return any additional field options that need to be included as a result of uniqueness constraints on the model. This is returned as a two-tuple of:

(‘dict of updated extra kwargs’, ‘mapping of hidden fields’)

_get_model_fields(self, field_names, declared_fields, extra_kwargs)

Returns all the model fields that are being mapped to by fields on the serializer class. Returned as a dict of ‘model field name’ -> ‘model field’. Used internally by get_uniqueness_field_options.

get_validators(self)

Determine the set of validators to use when instantiating serializer.

get_unique_together_validators(self)

Determine a default set of validators for any unique_together constraints.

get_unique_for_date_validators(self)

Determine a default set of validators for the following constraints:

  • unique_for_date
  • unique_for_month
  • unique_for_year
class HyperlinkedModelSerializer

Bases:rest_framework.serializers.ModelSerializer

A type of ModelSerializer that uses hyperlinked relationships instead of primary key relationships. Specifically:

  • A ‘url’ field is included instead of the ‘id’ field.
  • Relationships to other instances are hyperlinks, instead of primary keys.
get_default_field_names(self, declared_fields, model_info)

Return the default list of field names that will be used if the Meta.fields option is not specified.

build_nested_field(self, field_name, relation_info, nested_depth)

Create nested fields for forward and reverse relationships.