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

前端 未结 3 1384
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 05:30

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

3条回答
  •  心在旅途
    2020-12-29 05:53

    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

提交回复
热议问题