How do I do the equivalent of this SQL in django?
UPDATE table SET timestamp=NOW() WHERE ...
Particularly I want to set the datetime field using server's builtin function to get the system time from the server that the database was running on and not the time on the client machine.
I know you can execute the raw sql directly but I'm looking for a more portable solution since databases have different functions for getting the current datetime.
Edit: few people mentioned auto_now param. This updates the datetime on every modification while I want to update datetime only on certain occasions.
First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.
You want to add the auto_now field and set it to True. This will update with the current timestamp each time you update the model.
django default date to be in format %d-%m-%Y.
As j0ker said, if you want automatic update of the timestamp, use the auto_now
option. E.g. date_modified = models.DateTimeField(auto_now=True)
.
If you want to set the field to now only when the object is first created you should use:
date_modified = models.DateTimeField(auto_now_add=True)
Or if you want to do it manually, isn't it a simple assignment with python datetime.now()
?
from datetime import datetime obj.date_modified = datetime.now()
The accepted answer is outdated. Here's the current and most simple way of doing so:
>>> from django.utils import timezone >>> timezone.now() datetime.datetime(2018, 12, 3, 14, 57, 11, 703055, tzinfo=<UTC>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With