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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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)
Method 2
Just use TIMESTAMP type in MySQL. This field will update itself whenever the row is updated.
In the model
:
last_updated = peewee.TimestampField()
Method 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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0