在我的模型中,我有 2 个日期时间属性:
start_date
end_date
我想将结束日期算作一周 在 start_date 之后。
我怎样才能做到这一点?
请您参考如下方法:
如果您总是希望结束日期比开始日期晚一周,您可以做的是为您的模型创建一个自定义保存方法。 另一种选择是改用信号。结果是一样的,但由于您正在处理模型数据,我建议您使用自定义保存方法。它的代码看起来像这样:
class ModelName(models.Model):
...
def save(self):
# Place code here, which is excecuted the same
# time the ``pre_save``-signal would be
self.end_date = self.start_date + datetime.timedelta(days=7)
# Call parent's ``save`` function
super(ModelName, self).save()
您可以阅读有关如何在 django 文档中调用保存方法/信号的一些信息:http://docs.djangoproject.com/en/dev/ref/models/instances/
