django - 值更改后自动更新日期
问题描述:
在以下django模型中:
In the following django model:
class MyModel(models.Model):
published = models.BooleanField(default=False)
pub_date = models.DateTimeField('date published')
I希望使用当前日期自动更新pub_date字段,每当发布的字段更改为True时。
I want the pub_date field to be automatically updated with the current date, every time the published field changes to True.
什么是智能方式?
谢谢。
答
所有答案都很有用,但是我终于用这样做了:
All answers were useful, but I finally did it this way:
def save(self, *args, **kwargs):
if self.published and self.pub_date is None:
self.pub_date = timezone.now()
elif not self.published and self.pub_date is not None:
self.pub_date = None
super(Model, self).save(*args, **kwargs)