I am trying to add a creation_time
attribute to my documents. The following would be an example:
import datetime
class MyModel(mongoengine.Docu
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.
If you are using the timestamp field in a bunch of Documents you can keep your code DRY by creating an abstract Document instead.
from datetime import datetime
from mongoengine import Document
class CreateUpdateDocument(Document):
meta = {
'abstract': True
}
# last updated timestamp
updated_at = DateTimeField(default=datetime.now)
# timestamp of when entry was created
created_at = DateTimeField(default=datetime.now)
def save(self, *args, **kwargs):
if not self.created_at:
self.created_at = datetime.now()
self.updated_at = datetime.now()
return super(CreateUpdateDocument, self).save(*args, **kwargs)
You could use auto_now_add parameter as per documentation:
class MyModel(mongoengine.Document):
creation_date = mongo.DateTimeField(auto_now_add = True)
modified_date = mongo.DateTimeField(auto_now = True)