Sunday, November 17, 2024
Google search engine
HomeLanguagesString Fields in Serializers – Django REST Framework

String Fields in Serializers – Django REST Framework

In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. 
This article revolves around string Fields in Serializers in Django REST Framework. There are three major fields – CharField, EmailField and RegexField. 

CharField

CharField is used to store text representation. Optionally validates the text to be shorter than max_length and longer than min_length. It works the same as CharField – Django Models
It has the following arguments –  

  • max_length – Validates that the input contains no more than this number of characters.
  • min_length – Validates that the input contains no fewer than this number of characters.
  • allow_blank – If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • trim_whitespace – If set to True then leading and trailing whitespace is trimmed. Defaults to True.

Syntax – 

field_name = serializers.CharField(*args, **kwargs) 

EmailField

EmailField is also a text representation and it validates the text to be a valid e-mail address. It is same as EmailField – Django Models. It takes all of the arguments of CharField for same functionalities. 
Syntax – 

field_name = serializers.EmailField(*args, **kwargs) 

RegexField

As the name defines, RegexField matches the string to a particular regex, else raises an error. It is same as RegexField – Django Forms. It takes all of the arguments of CharField for same functionalities. 
Syntax – 

field_name = serializers.RegexField(*args, **kwargs)

 

How to use String Fields in Serializers ?

To explain the usage of String Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?
Now that you have a file called serializers in your project, let’s create a serializer with CharField, EmailField and RegexField as the fields. 

Python3




#import serializer from rest_framework
from rest_framework import serializers
 
class Geeks(object):
    def __init__(self, name, email, phone_number):
        self.name = name
        self.email = email
        self.phone_number = phone_number
 
# create a serializer
class GeeksSerializer(serializers.Serializer):
    # initialize fields
    name = serializers.CharField(max_length = 200)
    email = serializers.EmailField()
    phone_number = serializers.RegexField("[0-9]{10}")


Now let us create some objects and try serializing them and check if they are actually working, Run, –  

Python manage.py shell

Now, run following python commands in the shell 

# import everything from serializers
>>> from apis.serializers import *

# create a object of type Geeks
>>> obj = Geeks("Naveen", "abc@gmail.com", "1234567890")

# serialize the object
>>> serializer = GeeksSerializer(obj)

# print serialized data
>>> serializer.data
{'name': 'Naveen', 'email': 'abc@gmail.com', 'phone_number': '1234567890'}

Here is the output of all these operations on terminal – 

boolean-fields-in-serializers

Validation on String Fields

Note that prime motto of these fields is to impart validations, such as EmailField validates the data to email only. Let’s check if these validations are working or not – 

# Create a dictionary and add invalid values
>>> data={}
>>> data['name']="Naveen"
>>> data['email'] = "invalid_email"
>>> data['phone_number'] = "invalid_phone"

# dictionary created
>>> data
{'name': 'Naveen', 'email': 'invalid_email', 'phone_number': 'invalid_phone'}

# deserialize the data
>>> serializer = GeeksSerializer(data=data)

# check if data is valid
>>> serializer.is_valid()
False

# check the errors
>>> serializer.errors
{'email': [ErrorDetail(string='Enter a valid email address.', code='invalid')], 
'phone_number': [ErrorDetail(string='This value does not match the required pattern.',
code='invalid')]}

Here is the output of these commands which clearly shows email and phone_number as invalid – 

string-fields-in-serializers-Django-REST-Framework

Advanced concepts

Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work.
 

Core arguments in serializer fields

.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }  

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.
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments