Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Core arguments in serializer fields - Django REST Framework
Next article icon

Core arguments in serializer fields - Django REST Framework

Last Updated : 03 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer fields can use for efficiently manipulating data in and out of serializer. 

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; }  
ArgumentDescription
read_onlySet 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_onlySet 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.
requiredSetting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance.
defaultIf set, this gives the default value that will be used for the field if no input value is supplied.
allow_nullNormally 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.
sourceThe name of the attribute that will be used to populate the field.
validatorsA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return.
error_messagesA dictionary of error codes to error messages.
labelA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
help_textA text string that may be used as a description of the field in HTML form fields or other descriptive elements.
initialA value that should be used for pre-populating the value of HTML form fields.

read_only

Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. 

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. 

Defaults to False 
Syntax -  

read_only = True/False


Example - 

field_name = serializers.CharField(read_only = True) 

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. 

Defaults to False 
Syntax -  

write_only = True/False


Example - 

field_name = serializers.CharField(write_only = True) 

required

Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization. 

Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. 

Defaults to True. 

Syntax -  

write_only = True/False


Example - 

field_name = serializers.CharField(write_only = True) 

default

If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. 

The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. 

May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a requires_context = True attribute, then the serializer field will be passed as an argument. 

For example: 

class CurrentUserDefault:      """      May be applied as a `default=...` value on a serializer field.      Returns the current user.      """      requires_context = True        def __call__(self, serializer_field):          return serializer_field.context['request'].user  When serializing the instance, default will be used if the o

object attribute or dictionary key is not present in the instance. 

Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error. 

Syntax -  

default = value


Example - 

field_name = serializers.CharField(default = "Naveen") 

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. 

Note that, without an explicit default, setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization. 

Defaults to False 

Syntax -  

allow_null = True/False


Example - 

field_name = serializers.CharField(allow_null = True) 

source

The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email'). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal. 

The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. 

Defaults to the name of the field. 

Syntax -  

source = value


Example - 

field_name = serializers.CharField(source = "user.name") 

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. Validator functions should typically raise serializers.ValidationError, but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages. 

Syntax -  

validators = [function_1, function_2]


Example - 

field_name = serializers.CharField(validations = [validate_name, validate_username]) 

error_messages

A dictionary of error codes to error messages. It works the same way as error_messages – Django Built-in Field Validation 
Syntax -  

error_messages = {'argument':'message'}


Example - 

field_name = serializers.CharField(error_messages = {"unique":"Data should be unique"}) 

label

A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. It is same as label – Django Form Field Validation 

Syntax -  

label = value


Example - 

field_name = serializers.CharField(label = "Name") 

help_text

A text string that may be used as a description of the field in HTML form fields or other descriptive elements. It is same as help_text – Django Built-in Field Validation. 
Syntax -  

help_text = value


Example - 

field_name = serializers.CharField(help_text = "Enter only 10 characters") 

initial

A value that should be used for pre-populating the value of HTML form fields. It is same as initial – Django Form Field Validation. You may pass a callable to it, just as you may do with any regular Django Field: 
Syntax -  

initial = value


Example - 

import datetime  from rest_framework import serializers  class ExampleSerializer(serializers.Serializer):      day = serializers.DateField(initial=datetime.date.today)

Next Article
Core arguments in serializer fields - Django REST Framework

N

NaveenArora
Improve
Article Tags :
  • Python
  • Django-REST
  • rest-framework
Practice Tags :
  • python

Similar Reads

    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_n
    4 min read
    Date and time 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_n
    7 min read
    URL 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_n
    5 min read
    Serializer Fields - Django REST Framework
    Serializer comes with some fields (entries) that process data in and out of the serializer in Django REST Framework. The very motive of Serializing is to convert DB data to a datatype that can be used by javascript. For example, if you have a class with name Employee and its fields as Employee_id, E
    13 min read
    Pass Extra Arguments to Serializer Class in Django Rest Framework
    Django Rest Framework (DRF) is a powerful toolkit for building web APIs. It provides serializers that translate complex data types such as Django queryset into native Python data types, which can then be rendered into JSON or other content types. However, there are cases when we need to pass extra a
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences