ListField in serializers – Django REST Framework

29 Jul, 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 ListField in Serializers in Django REST Framework. 
ListField is basically a list field that validates the input against a list of objects.It has the following arguments –  
child – A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
allow_empty – Designates if empty lists are allowed.
min_length – Validates that the list contains no fewer than this number of elements.
max_length – Validates that the list contains no more than this number of elements.
Syntax –  
field_name = serializers.ListField(*args, **kwargs)
Example – For example, to validate a list of integers one might use something like the following:  
scores = serializers.ListField(
   child=serializers.IntegerField(min_value=0, max_value=100)
)
 
To explain the usage of ListField, 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 ListField as the fields.  
Python3
# import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object):    def __init__(self, integers):        self.integers = integers # create a serializerclass GeeksSerializer(serializers.Serializer):    # initialize fields    integers = serializers.ListField(    child = serializers.IntegerField(min_value = 0, max_value = 100)    )
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([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

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

# print serialized data
>>> serializer.data
{'integers': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
Here is the output of all these operations on terminal –  
 
Note that prime motto of these fields is to impart validations, such as ListField validates the data to list only. Let’s check if these validations are working or not –  
# Create a dictionary and add invalid values
>>> data = {}
>>> data['integers'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# dictionary created
>>> data
{'integers': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}

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

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

# check the errors
>>> serializer.errors
{}
Here is the output of these commands which clearly shows integers valid –  
 
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. 
 
gabaa406
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python