我可以为Django日期时间字段设置特定的默认时间吗? [英] Can I set a specific default time for a Django datetime field?
问题描述
我有一个事件模型,该事件几乎总是在晚上10:00开始,但有时可能更早/以后开始。为了方便管理员,我希望将时间默认为晚上10点,但可以根据需要进行更改;无论如何,都需要设置日期,因此它不需要默认值,但理想情况下,它将默认为当前日期。
I have a model for events which almost always start at 10:00pm, but may on occasion start earlier/later. To make things easy in the admin, I'd like for the time to default to 10pm, but be changeable if needed; the date will need to be set regardless, so it doesn't need a default, but ideally it would default to the current date.
我意识到我可以使用datetime.now完成后者,但是是否可以(以及如何)将时间设置为特定的默认值?
I realize that I can use datetime.now to accomplish the latter, but is it possible (and how) to I set the time to a specific default value?
更新:我得到的答案快于我能弄清哪个人完成了我要完成的工作...我可能应该更进一步我问之前的应用程序。
Update: I'm getting answers faster than I can figure out which one(s) does what I'm trying to accomplish...I probably should have been further along with the app before I asked. Thanks for the help in the meantime!
推荐答案
从Django文档中获取 Field.default
:
From the Django documents for Field.default
:
该字段的默认值。这可以是一个值或一个可调用的
对象。如果可调用,则每次创建新对象
时都会调用它。
The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
因此,请执行以下操作:
So do this:
from datetime import datetime, timedelta
def default_start_time():
now = datetime.now()
start = now.replace(hour=22, minute=0, second=0, microsecond=0)
return start if start > now else start + timedelta(days=1)
class Something(models.Model):
timestamp = models.DateTimeField(default=default_start_time)
这篇关于我可以为Django日期时间字段设置特定的默认时间吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!