Boolean 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 Boolean Fields in Serializers in Django REST Framework. There are two major fields for Boolean values – BooleanField and NullBooleanField.

BooleanField

A boolean field used to wrap True or False values. It works the same as BooleanField – Django Models. By default, serializers.BooleanField instances as created by default as False.
Syntax –

field_name = serializers.BooleanField()

NullBooleanField

A boolean field that accepts True, False and Null values. It works the same as NullBooleanField – Django Models. By default, serializers.NullBooleanField instances as created by deafult as none.
Syntax –

field_name = serializers.NullBooleanField()

How to use Boolean Fields in Serializers ?

To explain the usage of Boolean 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 BooleanField and NullBooleanField as the fields.

filter_none

edit
close

play_arrow

link
brightness_4
code

#import serializer from rest_framework
from rest_framework import serializers
  
class Geeks(object):
    def __init__(self, bool1, bool2):
        self.field_1 = bool1
        self.field_2 = bool2
  
# create a serializer
class GeeksSerializer(serializers.Serializer):
    # intialize fields
    field_1 = serializers.BooleanField()
    field_2 = serializers.NullBooleanField()

chevron_right


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(bool1 = True, bool2 = True)

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

# print serialized data
>>> serializer.data
{'field_1': True, 'field_2': True}

# another example
>>> obj1 = Geeks(bool1 = True, bool2 = None)
>>> serializer = GeeksSerializer(obj1)
>>> serializer.data
{'field_1': True, 'field_2': None}

Here is the output of all these operations on terminal –

boolean-fields-in-serializers

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.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Software Developer at GeeksForGeeks

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.