- September 3, 2008
- python save timestamp
- -1 (after 3 ratings)
A simple way to add
date_modified timestamps to a model. Adds a
date_created timestamp when the object is first created and adds a
date_modified timestamp whenever the item is saved.
Note: You might be tempted instead to use:
date_created=models.DateTimeField(default=datetime.now()) but that won't work as Python will calculate
datetime.now() only once when it interprets your model. This means that every object created will get the same
date_created timestamp until you restart your server.
1 2 3 4 5 6 7 8 9 10 11
from datetime import datetime class My_Model(models.Model): date_created = models.DateTimeField() date_modified = models.DateTimeField() def save(self): if self.date_created == None: self.date_created = datetime.now() self.date_modified = datetime.now() super(My_Model, self).save()