- Author:
- lindsayrgwatt
- Posted:
- September 3, 2008
- Language:
- Python
- Version:
- 1.0
- Score:
- -1 (after 3 ratings)
A simple way to add date_created
and 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()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
defaults might be also set to a callable object (function, method or class) which will be evaluated before saving the model instance. So you can use this instead:
#
It would be easier to use the
auto_now
andauto_now_add
arguments to theDateField
andDateTimeField
field types.#
I second stringify. I have been using the auto_now and auto_now_add fields for a while and have had no problems. Are they somehow different to this?
#
They were supposed to be deprecated but since they have made their way into 1.0 and Django is expected to stay backwards compatible for a while auto_now and auto_now_add might stay, I don't know...
#
Please login first before commenting.