本文介绍了peewee中的DateTimeField是否有自动更新选项,例如MySQL中的TimeStamp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次在MySQL中修改记录时,我都希望更新一个timestamp字段.

I would like a timestamp field updating each time the record is modified like in MySQL.

DateTimeField(default=datetime.datetime.now())只会在第一次创建时进行设置...

DateTimeField(default=datetime.datetime.now()) will only set it the first time it is created...

有没有简单的解决方案?唯一的解决方案是在MySQL数据库中手动设置Column选项吗?

Any have a simple solution?Is the only solution is to manually set the Column options in MySQL db?

推荐答案

您可以在模型类上覆盖save方法.

You can override the save method on your model class.

class Something(Model):
    created = DateTimeField(default=datetime.datetime.now)
    modified = DateTimeField

    def save(self, *args, **kwargs):
        self.modified = datetime.datetime.now()
        return super(Something, self).save(*args, **kwargs)

这篇关于peewee中的DateTimeField是否有自动更新选项,例如MySQL中的TimeStamp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 14:00