is there an auto update option for DateTimeField in peewee like TimeStamp in MySQL?

ぃ、小莉子 提交于 2019-12-20 11:36:26

问题


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

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

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


回答1:


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)



回答2:


Just use TIMESTAMP type in MySQL. This field will update itself whenever the row is updated.

In the model:

last_updated = peewee.TimestampField()



回答3:


You can also override the update method to provide.Just like what coleifer do:

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

    @classmethod
    def update(cls, *args, **kwargs):
        kwargs['modified'] = datetime.datetime.now()
        return super(Something, cls).save(*args, **kwargs)

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

You can also do the same thing on replace method



来源:https://stackoverflow.com/questions/18522600/is-there-an-auto-update-option-for-datetimefield-in-peewee-like-timestamp-in-mys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!