Mongoengine creation_time attribute in Document

josephmisiti picture josephmisiti · Nov 11, 2011 · Viewed 16.5k times · Source

I am trying to add a creation_time attribute to my documents. The following would be an example:

import datetime

class MyModel(mongoengine.Document):
    creation_date = mongo.DateTimeField()
    modified_date = mongo.DateTimeField(default=datetime.datetime.now)

Django models have built in parameter for their DateTimeField objects like add_now, etc., but MongoEngine does not support this.

I am wondering if best way to do this is the following:

m,created = MyModel.objects.get_or_create()
if created:
    m.creation_date = datetime.datetime.now()

or if there is a better, nicer way.

Answer

Willian picture Willian · Nov 15, 2011

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)