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

StackOverflow https://stackoverflow.com/questions/18522600

  •  26-06-2022
  •  | 
  •  

Question

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?

Était-ce utile?

La solution

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)

Autres conseils

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

In the model:

last_updated = peewee.TimestampField()

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top