About auto_now and auto_now_add fields
These fields are built into Django and have a precise purpose, namely to track when an object was last created or modified.
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
You can read more here about auto_now and auto_now_add fields
When I use auto_now and auto_now_add fields?
Usually, when I create a model (such as posts, products, etc.) I usually add the field:
created_at = models.DateTimeField(auto_now_add=True)
it helps me to sort them by the date they were created, for example, I display the newest first in the listings, like:
products = Product.objects.filter(category__in = categories,active=1,date_expired__gt=datetime.now()).order_by(‘-created_at’)
Be careful, these are Read-only fields
Because both of these fields (auto_now_add=True and auto_now=True) are read-only, assume editable=False, so they won’t show up in your Django admin view. Automatic updating of these fields are handled at the Django level.
So, if you need a “create date” field that you want to update, don’t use them.
How to allow manual editing of auto DateTime fields?
There are times when you need to change the create date value, for example, I wanted to repost a post, to be in front of the listing again.
My solution, in this case, was instead using auto_now_add=True, to declare the field like:
from django.utils import timezone
created_at = models.DateField(default=timezone.now)
After that, you have the option to edit the created_at field in the Django admin.
In the database table, the data look the same: the first row in the image below is with auto_now_add=True, the second row is with default=timezone.now
What was your solution? I invite you to share it in the comments:
Hello there!I hope you find this post useful!
I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.
If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!