the best practice for DateTimeField default value initialization

265 views
Skip to first unread message

Ryutlis

unread,
Feb 19, 2013, 10:12:00 AM2/19/13
to mongoeng...@googlegroups.com
Hi,

I don't know if you guys noticed, the given demo code ( http://mongoengine-odm.readthedocs.org/en/latest/guide/defining-documents.html#defining-a-document-s-schema ) is not showing the right way to initialize DataTimeField with default value.

Because datetime.now() is executed when initializing the "class" body, so once the class is created, all instances will get the same default "time" which is wrong.

What I can think of the best practice, is to add a method explicitly do this job, for instance:
@classmethod
def add(cls, attr1, attr2, attr3):
    obj = cls(attr1=attr1, attr2=attr2, attr3=attr3, time=datetime.now())
    obj.save()
    return obj

What's your take on this?

Russ Weeks

unread,
Feb 19, 2013, 10:33:07 AM2/19/13
to mongoeng...@googlegroups.com
Hi, Ryutlis,

Note that there's no brackets () after "default=datetime.datetime.now" in the demo code.  What's happening is that the callable object datetime.now is being passed in as the default value.  Mongoengine is smart enough to recognize this as a callable and use its return value as the default value for the datetime field.  The callable will be evaluated at a different time for each object, producing the expected result.

Regards,
-Russ


--
You received this message because you are subscribed to the Google Groups "MongoEngine Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoengine-us...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Ryutlis Wang

unread,
Feb 19, 2013, 10:41:14 AM2/19/13
to mongoeng...@googlegroups.com, rwe...@newbrightidea.com
Ah.....

My fault... I didn't notice that...

Thank you, Russ, for clearing this up!
Reply all
Reply to author
Forward
0 new messages