Core arguments in serializer fields – Django REST Framework

Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer fields can use for efficiently manipulating data in and out of serializer.

Core arguments in serializer fields

Argument Description
read_only Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization
write_only Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
required Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance.
default If set, this gives the default value that will be used for the field if no input value is supplied.
allow_null Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value.
source The name of the attribute that will be used to populate the field.
validators A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return.
error_messages A dictionary of error codes to error messages.
label A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
help_text A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
initial A value that should be used for pre-populating the value of HTML form fields.

read_only

Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any ‘read_only’ fields that are incorrectly included in the serializer input will be ignored.

Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.

Defaults to False
Syntax –

read_only = True/False

Example –



field_name = serializers.CharField(read_only = True)

write_only

Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

Defaults to False
Syntax –

write_only = True/False

Example –

field_name = serializers.CharField(write_only = True)

required

Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization.

Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.

Defaults to True.

Syntax –

write_only = True/False

Example –



field_name = serializers.CharField(write_only = True)

default

If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.

The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.

May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a requires_context = True attribute, then the serializer field will be passed as an argument.

For example:

class CurrentUserDefault:
    """
    May be applied as a `default=...` value on a serializer field.
    Returns the current user.
    """
    requires_context = True

    def __call__(self, serializer_field):
        return serializer_field.context['request'].user
When serializing the instance, default will be used if the o

bject attribute or dictionary key is not present in the instance.

Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.

Syntax –

default = value

Example –

field_name = serializers.CharField(deafult = "Naveen")

allow_null

Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value.

Note that, without an explicit default, setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization.



Defaults to False

Syntax –

allow_null = True/False

Example –

field_name = serializers.CharField(allow_null = True)

source

The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source=’get_absolute_url’), or may use dotted notation to traverse attributes, such as EmailField(source=’user.email’). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal.

The value source=’*’ has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.

Defaults to the name of the field.

Syntax –

source = value

Example –

field_name = serializers.CharField(source = "user.name")

validators

A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError, but Django’s built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages.

Syntax –



validators = [function_1, function_2]

Example –

field_name = serializers.CharField(validations = [validate_name, validate_username])

error_messages

A dictionary of error codes to error messages. It works the same way as error_messages – Django Built-in Field Validation
Syntax –

error_messages = {'argument':'message'}

Example –

field_name = serializers.CharField(error_messages = {"unique":"Data should be unique"})

label

A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. It is same as label – Django Form Field Validation

Syntax –

label = value

Example –

field_name = serializers.CharField(label = "Name")

help_text

A text string that may be used as a description of the field in HTML form fields or other descriptive elements. It is same as help_text – Django Built-in Field Validation.
Syntax –

help_text = value

Example –

field_name = serializers.CharField(help_text = "Enter only 10 characters")

initial

A value that should be used for pre-populating the value of HTML form fields. It is same as initial – Django Form Field Validation. You may pass a callable to it, just as you may do with any regular Django Field:
Syntax –

initial = value

Example –

import datetime
from rest_framework import serializers
class ExampleSerializer(serializers.Serializer):
    day = serializers.DateField(initial=datetime.date.today)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.