In my model I want to be able to input duration, like 2 years, 5 months, etc.
在我的模型中,我希望能够输入持续时间,比如2年,5个月等等。
In version 1.8 DurationField
was introduced so I tried using that:
在1.8版本的DurationField中,我尝试使用这个:
In my model I have user_validPeriod = models.DurationField()
在我的模型中,我有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
.
尝试从我的管理面板中添加一个新用户,如果我尝试在出现的文本框中输入2d或2天之类的东西,尽管我得到一个有效的持续时间。
Can someone provide me with an example of how this field is supposed to be used?
有人能给我举一个这个领域应该如何使用的例子吗?
1 个解决方案
#1
15
To use a DurationField in django 1.8 you have to use a python datetime.timedelta
instance like this:
要在django 1.8中使用DurationField,您必须使用python datetime。timedelta实例如下:
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.
更多信息在datetime。这里和这里的时间增量。
In your admin panel, you can enter a duration with a string with following format : hh:mm:ss
在您的管理面板中,您可以输入一个带有以下格式字符串的持续时间:hh:mm:ss
#1
15
To use a DurationField in django 1.8 you have to use a python datetime.timedelta
instance like this:
要在django 1.8中使用DurationField,您必须使用python datetime。timedelta实例如下:
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.
更多信息在datetime。这里和这里的时间增量。
In your admin panel, you can enter a duration with a string with following format : hh:mm:ss
在您的管理面板中,您可以输入一个带有以下格式字符串的持续时间:hh:mm:ss