问题
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