Django Model DurationField Explanation
Illustration of DurationField using an Example. Consider a project named w3wiki having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
Enter the following code into models.py file of geeks app.
Python3
from django.db import models from django.db.models import Model # Create your models here. class GeeksModel(Model): geeks_field = models.DurationField() |
Add the geeks app to INSTALLED_APPS
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'geeks' , ] |
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name = 'GeeksModel' , fields = [ ( 'id' , models.AutoField( auto_created = True , primary_key = True , serialize = False , verbose_name = 'ID' )), ( 'geeks_field' , models.DurationField()), ], ), ] |
Now run,
Python manage.py migrate
Thus, an geeks_field DurationField is created when you run migrations on the project. It is a field to store datetime.timedelta python object.
DurationField – Django Models
DurationField is a field for storing periods of time – modeled in Python by timedelta. When used on PostgreSQL, the data type used is an interval and on Oracle the data type is INTERVAL DAY(9) TO SECOND(6). Otherwise, a bigint of microseconds is used. DurationField basically stores a duration, the difference between two dates or times.
Syntax
field_name = models.DurationField(**options)