1

I have two models, both of which have a date field defaulting to the current date, whatever that may be. Today someone pointed out they were getting an error from one of them, which was setting dates to 19 December instead of 23 December (today at the time of writing).

I had thought both fields were set up identically so I checked for an unintended difference between the two and found one. But I was surprised because the 'working' one was the one that looked to me like it contained an error. The fields are set up like this:

# Working field
date_stamp = models.DateField(default=datetime.date.today)

# Broken field
date_statp = models.DateField(default=datetime.date.today())

I always thought the today function needed to be called to ensure the value wasn't cached. Is the reverse in fact true? Can someone explain how these two are actually interpreted on model instance creation?

cms_mgr
  • 1,977
  • 2
  • 17
  • 31

2 Answers2

5

The first field:

date_stamp = models.DateField(default=datetime.date.today)

takes a callback as a default value. That means that the function will be called everytime the default value needs to be filled.

The other one:

date_statp = models.DateField(default=datetime.date.today())

executes the function datetime.date.today, which returns the value of the date at that moment. So when Django initializes the models, it will set the default value to the date at that precise moment. This default value will be used untill Django reinitializes the models again, which is usually only at startup.

gitaarik
  • 42,736
  • 12
  • 98
  • 105
1

The class definition is run when the module is first imported, and the datetime.data.today() call is executed then. So, it runs when Django starts basically, and doesn't change after the first import.

Without parens, you set the default to the function object, a callable. When Django creates a new instance, and a default value is a callable, Django calls it and uses the return value as the default value. So that's what you want here -- no quotes.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79