Mar 2 2012

Learn about UUIDs

A great post about UUIDs, the various types, and how they are calculated.


Dec 12 2011

Jon Stewart’s Review of the Stories on the Lost RQ-170 Sentinel Drone

Jon Stewart does a hilarious review of the lost Sentinel drone.  Enjoy!

Dec 6 2011

How to Properly Set a Default Value for a DateTimeField in Django

It is pretty common to have database fields to track the created and updated dates for objects in your model.  But how do you make sure that every time a new object is created they receive the current date and time?  That’s easy: just set the default option for your DateTimeField, such as

created_date = models.DateTimeField('date created', default=datetime.now())

That’s exactly what I’ve done and while developing with Django’s internal development server it works great!  Then I deployed my project to production which uses Apache with mod_wsgi and I noticed that the timestamps were wrong.  They seemed to coincide with when I had restarted Apache.  I googled things like “django datetime incorrect” and found other people with the same problem.  Some people resorted to overriding the save method, while others created database triggers to update with the current date and time on insert.  I didn’t think I should have to override the save method for something like this and I certainly didn’t want to start creating database triggers (I use Django to keep all of my logic in one place and abstract away my database!).

After doing some more research, it turns out that while I had read the manual, I didn’t understand the manual.  Referring to the Django docs for the default field option for models

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

you can see that you can either pass a value or callable object.  I thought that I was telling Django to evaluate the current time every time a new object was created, but I wasn’t.  What instead was happening was datetime.now() was being evaluated when the class was first instantiated (when the web server was restarted!) and that value was being reused every time a new object was created.  I needed to instead pass a callable object that would return the current date and time whenever a new object was created.

I updated my code from this

created_date = models.DateTimeField('date created', default=datetime.now())

to this

created_date = models.DateTimeField('date created', default=datetime.now)

Note that datetime.now() is evaluated only once when the class is instantiated and datetime.now is a callable object that is evaluated each time a new object is created.  Including the parenthesis executes the function and passes the result while excluding the parenthesis passes the function itself.  This was a good lesson to learn and will definitely help me with my future Django coding.  Hopefully this tidbit helps someone else as well.