django - 值更改后自动更新日期 [英] django - update date automatically after a value change
本文介绍了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)
这篇关于django - 值更改后自动更新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文