In my model I want to be able to input duration, like 2 years, 5 months, etc.
In version 1.8 DurationField was introduced so I tried using that:
In my model I have
user_validPeriod = models.DurationField()
Trying to add a new User from my admin panel, If I try typing something like 2d or 2 days in the appearing text-field though I get Enter a valid duration
.
Can someone provide me with an example of how this field is supposed to be used?
DurationField is used for storing python datetime. timedelta instance in the database. One can store any type of duration based on time or date in the database. To know more about datetime. timedelta, check out Python | datetime.
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model .
To use a DurationField in django 1.8 you have to use a python datetime.timedelta
instance like this:
Considering this model :
from django.db import models class MyModel(models.Model): duration = models.DurationField()
You can set a duration this way :
import datetime my_model = MyModel() my_model.duration = datetime.timedelta(days=20, hours=10)
And query it this way :
# Equal durations = MyModel.objects.filter(duration=datetime.timedelta(*args, **kwargs)) # Greater than or equal durations = MyModel.objects.filter(duration__gte=datetime.timedelta(*args, **kwargs)) # Less than or equal durations = MyModel.objects.filter(duration__lte=datetime.timedelta(*args, **kwargs))
More info on datetime.timedelta here and on DurationField here.
In your admin panel, you can enter a duration with a string with following format : [DD] [[hh:]mm:]ss
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With