How to create a Django model with a DurationField



Image not found!!

In Django, you can create a model with a DurationField to store a duration of time. Here's how you can create a Django model with a DurationField:

python
from django.db import models class MyModel(models.Model): duration = models.DurationField()

In this example, MyModel is a Django model with a field named duration, which is a DurationField. This field can store a duration of time, such as "5 days" or "2 hours and 30 minutes".

You can further customize the DurationField by specifying default, blank, null, verbose_name, etc., just like any other Django model field.

Here's an example with some additional options:

python
class MyModel(models.Model): duration = models.DurationField(default=datetime.timedelta(days=1), verbose_name='Duration', blank=True, null=True)

In this example:

  • default sets the default duration value for this field.
  • verbose_name specifies a human-readable name for the field in forms and admin interfaces.
  • blank=True allows the field to be left blank in forms.
  • null=True allows the field to be stored as NULL in the database, if no duration is provided.

After defining your model, remember to run python manage.py makemigrations and python manage.py migrate to apply these changes to your database schema.