在Django模型中,如何使用timezone.now
增加日期字段?
工作:
end_date = models.DateTimeField(default=timezone.now() + timezone.timedelta(days=365))
不工作
end_date = models.DateTimeField(default=timezone.now + timezone.timedelta(days=365))
我认为timezone.now
是每次创建对象时都会运行的函数。这样就会发生错误。
答案 0 :(得分:3)
你可以使用一个功能:
def f():
return timezone.now() + timezone.timedelta(days=365)
...
end_date = models.DateTimeField(default=f)
该时区的当前时间是在默认情况下创建新end_date
的任何时候添加的timedelta:
>>> from django.utils import timezone
>>> from datetime import timedelta
>>> def f():
... return timezone.now() + timezone.timedelta(days=365)
...
>>> f()
datetime.datetime(2018, 6, 25, 19, 42, 49, 761389, tzinfo=<UTC>)
>>> f()
datetime.datetime(2018, 6, 25, 19, 43, 2, 953158, tzinfo=<UTC>)
使用Django运行示例:
In [1]: from testapp import models
In [2]: models.Test.objects.create().date_added
Out[2]: datetime.datetime(2018, 6, 25, 20, 5, 28, 316214, tzinfo=<UTC>)
In [3]: models.Test.objects.create().date_added
Out[3]: datetime.datetime(2018, 6, 25, 20, 5, 33, 114624, tzinfo=<UTC>)
答案 1 :(得分:0)
一个好方法是使用post_save
信号。导入它
from django.db.models.signals import post_save
然后创建一个这样的处理函数:
def handler_function(sender, instance, created, **kwargs):
if sender == YourModel and created:
instance.end_date = timezone.now() + timezone.timedelta(days=365)
instance.save()
post_save.connect(handler_function, sender=YourModel)
这肯定会起作用,我希望这也适用于你的情况。如果您需要进一步的帮助,请告诉我们!