Sunday, November 17, 2024
Google search engine
HomeLanguagesDate and time fields in serializers – Django REST Framework

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_name, date, etc. Then, you would need AutoField, CharField and DateField 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 Date and time Fields in Serializers in Django REST Framework. There are four major fields – DateTimeField, DateField, TimeField and DurationField.
 

DateTimeField

DateTimeField is a serializer field used for date and time representation. It is same as – DateTimeField – Django Models
It has the following arguments – 
 

  • format – A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer.
  • input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’].
  • default_timezone – A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive.

Syntax – 
 

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

 

DateField

DateField is a serializer field used for date representation. Often, one needs to store date such as in a blog model every post’s date needs to be stored. This field is same as DateField – Django Models 
It has the following arguments – 
 

  • format – A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.
  • input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’].

Syntax – 
 

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

 

TimeField

Timefield is a serializer field used for time representation. Often, one needs to store date such as in a blog model every post’s time needs to be stored.
It has the following arguments – 
 

  • format – A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer.
  • input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’].

Syntax – 
 

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

 

DurationField

DurationField is a serializer field used for duration representation. This field is same as DurationField – Django Models 
It has the following arguments – 
 

  • max_value Validate that the duration provided is no greater than this value.
  • min_value Validate that the duration provided is no less than this value.

Syntax – 
 

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

 

How to use Date and Time Fields in Serializers ?

To explain the usage of Date and Time 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 DatetimeField, DateField, TimeField and DurationField. 
 

Python3




# import serializer from rest_framework
from rest_framework import serializers
 
class Geeks(object):
    def __init__(self, date_time, date, time, duration):
        self.date_time = date_time
        self.date = date
        self.time = time
        self.duration = duration
 
# create a serializer
class GeeksSerializer(serializers.Serializer):
    # initialize fields
    date_time = serializers.DateTimeField()
    date = serializers.DateField()
    time = serializers.TimeField()
    duration = serializers.DurationField()


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 datetime
>>> from datetime import *

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

# create a object of type Geeks
>>> obj = Geeks(datetime.now(), date.today(), time(), timedelta(days=-1))

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

# print serialized data
>>> serializer.data
{'date_time': '2020-03-22T13:17:27.853707Z',
 'date': '2020-03-22', 'time': '00:00:00', 
 'duration': '-1 00:00:00'}

Here is the output of all these operations on terminal – 
 

date-and-time-fields-in-serializers-Django-REST-Farmweork

 

Validation on Date and time Fields

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

# Create a dictionary and add invalid values
>>> data={}
>>> data['date_time'] = "invalid_date_time"
>>> data['date'] = date.today()
>>> data['time'] = time()
>>> data['duration'] = "invalid_duration"

# dictionary created
>>> data
{'date_time': 'invalid_date_time', 
'date': datetime.date(2020, 3, 22),
'time': datetime.time(0, 0), 
'duration': 'invalid_duration'}

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

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

# check the errors
>>> serializer.errors
{'date_time': [ErrorDetail(string='Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].', code='invalid')], 'duration': [ErrorDetail(strin
g='Duration has wrong format. Use one of these formats instead: [DD] [HH:[MM:]]ss[.uuuuuu].', code='invalid')]}

Here is the output of these commands which clearly shows date_time and duration as invalid – 
 

date-and-time-fields-in-serializers

 

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

 

 

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.

 

RELATED ARTICLES

Most Popular

Recent Comments