Current DateTime for default value in a Model? Use callables
Published in
1 min readApr 16, 2016
So. Let’s say that you have:
# app/models.py
from django.db import models
from datetime import datetimeclass Book(models.Model):
name = models.CharField(max_length=128)
release_date = models.DateTimeField(default=datetime.now())
With release_date getting the current date and time by default.
That will not work, and is so subtle the error that you might fall for it as I did.
Do you see it? What is happening is that ‘datetime.now()’ is evaluated once (when models.py gets loaded) and not each time you need to create a new Book instance.
Here is the correct way:
# app/models.py
from django.db import models
from datetime import datetimeclass Book(models.Model):
name = models.CharField(max_length=128)
release_date = models.DateTimeField(default=datetime.now)
Yep. No parenthesis, now you are passing datetime.now as callable as default value, and datetime.now() will get invoked each time a Book is instantiated.