Timestamps in Model

 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

  1. datetime.time/datetime.datetime to Unix Epoch (with microsecond support) by sleepycal 3 years ago
  2. ActiveManager: filter objects depending on publication and/or expiration dates by haplo 4 years, 10 months ago
  3. Admin page without inlines dinamically by davmuz 11 months, 1 week ago
  4. Fix for the bad behaviour of GenericForeignKey field by pinkeen 2 years, 4 months ago
  5. "Approved" field with timestamp by miracle2k 5 years, 10 months ago

Comments

Archatas (on September 3, 2008):

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:

date_created=models.DateTimeField(default=datetime.now)

#

stringify (on September 3, 2008):

It would be easier to use the auto_now and auto_now_add arguments to the DateField and DateTimeField field types.

#

aarond10ster (on September 3, 2008):

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?

#

mk (on September 3, 2008):

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...

#

(Forgotten your password?)