在下面的django模型中:
class MyModel(models.Model):
published = models.BooleanField(default=False)
pub_date = models.DateTimeField('date published')
我希望 pub_date 字段在每次发布的字段更改为 True 时自动更新为当前日期。
聪明的方法是什么?
谢谢。
最佳答案
您想添加 auto_now 字段并将其设置为 True。每次更新模型时,这将更新为当前时间戳。
pub_date = models.DateTimeField('date_published', auto_now=True)
你可以阅读它here
编辑
抱歉,当 published 的值设置为 True 时,您真的只想更改时间戳。一个非常简单的方法是获取模型的原始值,然后覆盖保存方法,以便在将其设置为 True 时进行更新。这是您添加到代码中的内容:
class MyModel(models.Model):
published = models.BooleanField(default=False)
pub_date = models.DateTimeField('date published')
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self._published = self.published
def save(self, *args, **kwargs):
if not self._published and self.published:
self.pub_date = django.timezone.now()
super(MyModel, self).save(*args, **kwargs)
关于python - django - 值更改后自动更新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858418/