Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use DurationField in my model?

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.

enter image description here

Can someone provide me with an example of how this field is supposed to be used?

like image 926
ealiaj Avatar asked May 13 '15 18:05

ealiaj


People also ask

What is DurationField?

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.

What is a model Django?

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 .


1 Answers

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

like image 74
Charlesthk Avatar answered Sep 23 '22 11:09

Charlesthk