I am trying to add a creation_time attribute to my documents. The following would be an example:
import datetime
class MyModel(mongoengine.Docu
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.