Serializers – Django REST Framework
This article revolves around how to use serializers from scratch in Django REST Framework to advanced serializer fields and arguments. It assumes one is familiar with How to start a project with Django REST Framework ?
- Creating and Using Serializers
- Serializer Fields
- Core arguments in serializer fields
Creating and Using Serializers
Creating a basic Serializer
To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django.
This way one can declare serializer for any particular entity or object based on fields required. Serializers can be used to serialize as well as deserialize the data.
Using Serializer to serialize data
One can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class. Let’s create a Comment class first to create a object of type comment that can be understood by our serializer.
Now that our object is ready, let’s try serializing this comment object. Run following command,
Python manage.py shell
Now run the following code
# import comment serializer >>> from apis.serializers import CommentSerializer # import datetime for date and time >>> from datetime import datetime # create a object >>> class Comment(object): ... def __init__(self, email, content, created=None): ... self.email = email ... self.content = content ... self.created = created or datetime.now() ... # create a comment object >>> comment = Comment(email@example.com', content='foo bar') # serialize the data >>> serializer = CommentSerializer(comment) # print serialized data >>> serializer.data
Now let’s check output for this,
To check more on how to create and use a serializer visit – Creating and Using Serializers
The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.
The ModelSerializer class is the same as a regular Serializer class, except that:
- It will automatically generate a set of fields for you, based on the model.
- It will automatically generate validators for the serializer, such as unique_together validators.
- It includes simple default implementations of .create() and .update().
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
To checkout how to use ModelSerializer in your project, visit – ModelSerializer in serializers – Django REST Framework.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.
To checkout how to use HyperLinkedModelSerializer in your project, visit – HyperlinkedModelSerializer in serializers – Django REST Framework.
|BooleanField||A boolean field used to wrap True or False values.|
|NullBooleanField||A boolean field that accepts True, False and Null values.|
|CharField||CharField is used to store text representation.|
|EmailField||EmailField is also a text representation and it validates the text to be a valid e-mail address.|
|RegexField||As the name defines, RegexField matches the string to a particular regex, else raises an error.|
|URLField||URLField is basically a RegexField that validates the input against a URL matching pattern.|
|SlugField||SlugField is a RegexField that validates the input against the pattern [a-zA-Z0-9_-]+.|
|IPAddressField||IPAddressField is a field that ensures the input is a valid IPv4 or IPv6 string.|
|IntegerField||IntegerField is basically a integer field that validates the input against Python’s int instance.|
|FloatField||FloatField is basically a float field that validates the input against Python’s float instance.|
|DecimalField||DecimalField is basically a decimal field that validates the input against Python’s decimal instance.|
|DateTimeField||DateTimeField is a serializer field used for date and time representation.|
|DateField||DateField is a serializer field used for date representation.|
|TimeField||Timefield is a serializer field used for time representation.|
|DurationField||DurationField is a serializer field used for duration representation.|
|ChoiceField||ChoiceField is basically a CharField that validates the input against a value out of a limited set of choices.|
|MultipleChoiceField||MultipleChoiceField is basically a CharField that validates the input against a set of zero, one or many values, chosen from a limited set of choices.|
|FileField||FileField is basically a file representation. It performs Django’s standard FileField validation.|
|ImageField||ImageField is an image representation.It validates the uploaded file content as matching a known image format.|
|ListField||ListField is basically a list field that validates the input against a list of objects.|
|JSONField||JSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives.|
|HiddenField||HiddenField is a field class that does not take a value based on user input, but instead takes its value from a default value or callable.|
|DictField||DictField is basically a dictionary field that validates the input against a dictionary of objects.|
Core arguments in serializer fields
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.
|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.|