Reputation: 396
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?
Upvotes: 24
Views: 10165
Reputation: 11
from datetime import datetime
from peewee import (AutoField, CharField, DateTimeField, FloatField,
IntegerField, Model, MySQLDatabase, TextField, SQL)
from config import DataBaseConfig
mysql_client = MySQLDatabase(
"your_database_name",
host=DataBaseConfig.host,
port=DataBaseConfig.port,
user=DataBaseConfig.user,
password=DataBaseConfig.password,
)
class CommonModel(Model):
id = AutoField(verbose_name="primary key")
create_time = DateTimeField(default=datetime.now, verbose_name="create time")
update_time = DateTimeField(default=datetime.now, verbose_name="update time", constraints=[SQL('ON UPDATE CURRENT_TIMESTAMP')])
class Meta:
database = mysql_client
You can refer to this document. Single-column indexes and constraints!
Upvotes: 1
Reputation: 29
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
Upvotes: 1
Reputation: 36000
Just use TIMESTAMP type in MySQL. This field will update itself whenever the row is updated.
In the model
:
last_updated = peewee.TimestampField()
Upvotes: 4
Reputation: 26215
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)
Upvotes: 39