When to use django.db.models.LazyDate() and when datetime.now()?

9 views
Skip to first unread message

Rudolph

unread,
Jun 9, 2006, 8:35:38 AM6/9/06
to Django users
Hi,

I understand why we have the django.db.models.LazyDate(): it's to make
sure we get the datetime value at execution time and not at "compile"
time. The docs tell you to use it for "limit_choices_to", but should I
also use it when I want the default value of a DateTimeField to be
"now". And how about inside model methods, manager methods and view
functions? I guess one should/can use datetime.now() in those places,
but I'm not sure. Can anyone provide some info on this subject? It
might also be interesting to add this to the docs.

Thanks, Rudolph

Luke Plant

unread,
Jun 10, 2006, 10:19:12 AM6/10/06
to django...@googlegroups.com

For DateTimeFields, please have a look at the docs:
http://www.djangoproject.com/documentation/model_api/

Also, the 'default' value can be a callable (I think), so you can use
'default=datetime.now'. (NB: not 'default=datetime.now()')

When thinking about lazy objects, the rules are the same as normal
Python. You have to think about when the code will be evaluated. Note
this is different from 'compiled' -- Python code is compiled first of
all to bytecode, and usually stored in a .pyc file. Before it can be
used, the bytecode must be evaluated. This occurs when the module is
first imported in a Python process, and it creates at runtime all the
classes and functions that exist in that module.

Example:
### mymodule.py

from datetime import datetime
module_created = datetime.now()

class MyClass:
class_created = datetime.now()
def __init__(self):
self.instance_created = datetime.now()

def mydate():
return datetime.now()

# Advanced example
def create_a_class():
class SomeClass:
class_created = datetime.now()
return SomeClass

### end


From some other code, or a prompt, you will get this:

>>> mymodule.module_created
<The datetime the module was imported>
>>> mymodule.MyClass.class_created
<The datetime the module was imported>
>>> m = MyClass()
>>> m.instance_created
<2 seconds ago i.e. when you called MyClass.__init__()>
>>> mydate()
<Now>
>>> create_a_class().class_created
<Now>

LazyDate exists for the first two cases, which includes the definition
of models like in Django. It isn't needed for the rest. Don't worry
if you didn't understand the last one, but it's actually consistent.

(There is one more case to worry about - default arguments to functions
and methods are evaluated when the function is defined, not when it is
called.)


Luke

--
The probability of someone watching you is proportional to the
stupidity of your action.

Luke Plant || L.Plant.98 (at) cantab.net || http://lukeplant.me.uk/

Rudolph

unread,
Jun 10, 2006, 10:32:19 AM6/10/06
to Django users
Thanks Luke, very nicely explained!

Rudolph

Reply all
Reply to author
Forward
0 new messages