我应该如何在我的模型中使用 DurationField?

编程入门 行业动态 更新时间:2024-10-17 09:49:32
本文介绍了我应该如何在我的模型中使用 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()

尝试从我的管理面板添加一个新的 用户,如果我尝试在出现的文本中输入类似 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?

本文发布于:2023-11-17 12:28:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1610004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   如何在   DurationField

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!