在我的模型中,我希望能够输入持续时间,例如 2 年、5 个月 等
In my model I want to be able to input duration, like 2 years, 5 months, etc.
在 1.8 版中引入了 DurationField,所以我尝试使用它:
In version 1.8 DurationField was introduced so I tried using that:
在我的模型中我有
user_validPeriod = models.DurationField()尝试从我的管理面板添加一个新的 用户,如果我尝试在出现的文本中输入类似 2d 或 2 days 的内容 -字段虽然我得到输入有效的持续时间.
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?
推荐答案要在 django 1.8 中使用 DurationField,您必须像这样使用 python datetime.timedelta 实例:
To use a DurationField in django 1.8 you have to use a python datetime.timedelta instance like this:
考虑这个模型:
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)然后这样查询:
# 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))有关 datetime.timedelta 的更多信息 此处 和 DurationField这里.
More info on datetime.timedelta here and on DurationField here.
在您的管理面板中,您可以使用以下格式的字符串输入持续时间:[DD] [[hh:]mm:]ss
In your admin panel, you can enter a duration with a string with following format : [DD] [[hh:]mm:]ss
更多推荐
我应该如何在我的模型中使用 DurationField?
发布评论