我应该如何在模型中使用DurationField? [英] How should I use DurationField in my model?

查看:318
本文介绍了我应该如何在模型中使用DurationField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中,我希望能够输入持续时间,例如 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()

尝试添加新的 User ,如果我尝试在出现的文本字段中输入类似 2d 2天的内容,尽管我得到输入有效期限

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆