Correct Way To Use A Default Date In A Django Model
Solution 1:
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.
Solution 2:
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.
Post a Comment for "Correct Way To Use A Default Date In A Django Model"