Choice Selection Fields in serializers - Django REST Framework - GeeksforGeeks

04 Aug, 2021
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 Choice Selection Fields in Serializers in Django REST Framework. There are two major fields – Choice and MultipleChioceField. 
ChoiceField is basically a CharField that validates the input against a value out of a limited set of choices. This field is same as ChoiceField – Django Forms.It has the following arguments –  
choices – A list of valid values, or a list of (key, display_name) tuples.
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.
html_cutoff – If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
html_cutoff_text – If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to “More than {count} items...”
Syntax –  
field_name = serializers.ChoiceField(*args, **kwargs)
ChoiceField is basically a CharField that validates the input against a set of zero, one or many values, chosen from a limited set of choices. This field is same as MultipleChoiceField – Django Forms.Syntax –  
field_name = serializers.MultipleChoiceField(*args, **kwargs)
 
To explain the usage of Choice Selection 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 ChoiceField and MultipleChoiceField as the fields.  
Python3
# import serializer from rest_frameworkfrom rest_framework import serializers  class Geeks(object):    def __init__(self, choices, multiplechoices):        self.choices = choices        self.multiplechoices = multiplechoices  # create a tupleGEEKS_CHOICES =(     ("1", "One"),     ("2", "Two"),     ("3", "Three"),     ("4", "Four"),     ("5", "Five"), )  # create a serializerclass GeeksSerializer(serializers.Serializer):    # initialize fields    choices = serializers.ChoiceField(                        choices = GEEKS_CHOICES)    multiplechoices = serializers.MultipleChoiceField(                        choices = GEEKS_CHOICES)
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("One", ["One", "Two"])

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

# print serialized data
>>> serializer.data
{'choices': 'One', 'multiplechoices': {'Two', 'One'}}
Here is the output of all these operations on terminal –  
 
Note that prime motto of these fields is to impart validations, such as ChoiceField validates the data to a selected give choices only. Let’s check if these validations are working or not –  
# Create a dictionary and add invalid values
>>> data={}
>>> data['choices'] = "Naveen"
>>> data['multiplechoices'] = ["One", "Two"]

# dictionary created
>>> data
{'choices': 'Naveen', 'multiplechoices': ['One', 'Two']}

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

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

# check the errors
>>> serializer.errors
{'choices': [ErrorDetail(string='"Naveen" is not a valid choice.', code='invalid_choice')],
'multiplechoices': [ErrorDetail(string='"One" is not a valid choice.', code='invalid_choice')]}
Here is the output of these commands which clearly shows email and phone_number as invalid –  
 
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.  
sagar0719kumar
gabaa406
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python