django set DateTimeField to server's current time

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.


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>)

You can use database function Now starting Django 1.9:

from django.db.models.functions import Now
Model.objects.filter(...).update(timestamp=Now())