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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30222660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:05:44  来源:igfitidea点击:

How should I use DurationField in my model?

pythondjangodjango-models

提问by ealiaj

In my model I want to be able to input duration, like 2 years, 5 months, etc.

在我的模型中,我希望能够输入持续时间,如2 年5 个月等。

In version 1.8DurationFieldwas introduced so I tried using that:

1.8DurationField中引入了所以我尝试使用它:

In my model I have user_validPeriod = models.DurationField()

在我的模型中,我有 user_validPeriod = models.DurationField()

Trying to add a new Userfrom my admin panel, If I try typing something like 2dor 2 daysin the appearing text-field though I get Enter a valid duration.

尝试从我的管理面板添加新用户,如果我尝试在出现的文本字段中输入2d2 days之类的内容,但我得到Enter a valid duration.

enter image description here

在此处输入图片说明

Can someone provide me with an example of how this field is supposed to be used?

有人可以为我提供一个应该如何使用该字段的示例吗?

采纳答案by Charlesthk

To use a DurationField in django 1.8 you have to use a python datetime.timedeltainstance like this:

要在 django 1.8 中使用 DurationField,您必须使用这样的 pythondatetime.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 hereand on DurationField here.

在datetime.timedelta更多信息这里和DurationField这里

In your admin panel, you can enter a duration with a string with following format : [DD] [[hh:]mm:]ss

在您的管理面板中,您可以使用以下格式的字符串输入持续时间: [DD] [[hh:]mm:]ss