Mongoengine creation_time attribute in Document
You could override the save method.
class MyModel(mongoengine.Document): creation_date = mongo.DateTimeField() modified_date = mongo.DateTimeField(default=datetime.datetime.now) def save(self, *args, **kwargs): if not self.creation_date: self.creation_date = datetime.datetime.now() self.modified_date = datetime.datetime.now() return super(MyModel, self).save(*args, **kwargs)
As an aside, the creation time is stamped into the _id
attribute - if you do:
YourObject.id.generation_time
Will give you a datetime stamp.
One nice solution is reusing a single signal handler for multiple documents.
class User(Document): # other fields... created_at = DateTimeField(required=True, default=datetime.utcnow) updated_at = DateTimeField(required=True)class Post(Document): # other fields... created_at = DateTimeField(required=True, default=datetime.utcnow) updated_at = DateTimeField(required=True)def update_timestamp(sender, document, **kwargs): document.updated_at = datetime.utcnow()signals.pre_save.connect(update_timestamp, sender=User)signals.pre_save.connect(update_timestamp, sender=Post)
Be careful to assign a callable and not a fixed-value as the default, for example default=datetime.utcnow
without ()
. Some of the other answers on this page are incorrect and would cause created_at
for new documents to always be set to the time your app was first loaded.
It's also always better to store UTC dates (datetime.utcnow
instead of datetime.now
) in your database.