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

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

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

发布评论

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

>www.elefans.com

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