django 将 DateTimeField 设置为数据库服务器的当前时间



如何在django中执行相同的SQL ?

UPDATE table SET timestamp=NOW() WHERE ...

我特别想设置datetime字段,使用服务器的内置函数从数据库运行的服务器获取系统时间,而不是客户端机器上的时间。

我知道你可以直接执行原始sql,但我正在寻找一个更可移植的解决方案,因为数据库有不同的功能来获取当前日期时间。

编辑:很少有人提到auto_now参数。这将在每次修改时更新datetime,而我希望仅在某些场合更新datetime。

正如j0ker所说,如果您想要自动更新时间戳,请使用auto_now选项。例:date_modified = models.DateTimeField(auto_now=True)

如果你想将字段设置为现在,只有当对象第一次创建时,你应该使用:

date_modified = models.DateTimeField(auto_now_add=True)

或者如果你想手工做,这不是一个简单的python datetime.now()赋值吗?

from datetime import datetime
obj.date_modified = datetime.now()

接受的答案已经过时了。下面是当前最简单的方法:

>>> from django.utils import timezone
>>> timezone.now()
datetime.datetime(2018, 12, 3, 14, 57, 11, 703055, tzinfo=<UTC>)

你可以使用数据库函数

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

我是这样解决这个问题的。希望它能节省一些人的时间:

from django.db import models
class DBNow(object):
    def __str__(self):
        return 'DATABASE NOW()'
    def as_sql(self, qn, val):
        return 'NOW()', {}
    @classmethod
    def patch(cls, field):
        orig_prep_db = field.get_db_prep_value
        orig_prep_lookup = field.get_prep_lookup
        orig_db_prep_lookup = field.get_db_prep_lookup
        def prep_db_value(self, value, connection, prepared=False):
            return value if isinstance(value, cls) else orig_prep_db(self, value, connection, prepared)
        def prep_lookup(self, lookup_type, value):
            return value if isinstance(value, cls) else orig_prep_lookup(self, lookup_type, value)
        def prep_db_lookup(self, lookup_type, value, connection, prepared=True):
            return value if isinstance(value, cls) else orig_db_prep_lookup(self, lookup_type, value, connection=connection, prepared=True)
        field.get_db_prep_value = prep_db_value
        field.get_prep_lookup = prep_lookup
        field.get_db_prep_lookup = prep_db_lookup
# DBNow Activator
DBNow.patch(models.DateTimeField)

然后使用DBNow()作为需要更新和过滤的值:

books = Book.objects.filter(created_on__gt=DBNow())
    or:
book.created_on = DBNow()
book.save()

您可以使用下面的内容来创建一个自定义值,以表示数据库上当前时间的使用情况:

class DatabaseDependentValue(object):
    def setEngine(self, engine):
        self.engine = engine
    @staticmethod
    def Converter(value, *args, **kwargs):
        return str(value)
class DatabaseNow(DatabaseDependentValue):
    def __str__(self):
        if self.engine == 'django.db.backends.mysql':
            return 'NOW()'
        elif self.engine == 'django.db.backends.postgresql':
            return 'current_timestamp'
        else:
            raise Exception('Unimplemented for engine ' + self.engine)
django_conversions.update({DatabaseNow: DatabaseDependentValue.Converter})
def databaseDependentPatch(cls):
    originalGetDbPrepValue = cls.get_db_prep_value
    def patchedGetDbPrepValue(self, value, connection, prepared=False):
        if isinstance(value, DatabaseDependentValue):
            value.setEngine(connection.settings_dict['ENGINE'])
            return value
        return originalGetDbPrepValue(self, value, connection, prepared)
    cls.get_db_prep_value = patchedGetDbPrepValue

然后能够在DateTimeField上使用DatabaseNow:

databaseDependentPatch(models.DateTimeField)

然后反过来又允许你做一个漂亮而干净的:

class Operation(models.Model):
    dateTimeCompleted = models.DateTimeField(null=True)
    # ...
operation = # Some previous operation
operation.dateTimeCompleted = DatabaseNow()
operation.save()

我的调整代码与sqlite, mysql和postgresql一起工作,并且比建议的解决方案更干净。

class DBCurrentTimestamp:
    def __str__(self):
        return 'DATABASE CURRENT_TIMESTAMP()'
    def as_sql(self, qn, connection):
        return 'CURRENT_TIMESTAMP', {}
    @classmethod
    def patch(cls, *args):
        def create_tweaked_get_db_prep_value(orig_get_db_prep_value):
            def get_db_prep_value(self, value, connection, prepared=False):
                return value if isinstance(value, cls) else orig_get_db_prep_value(self, value, connection, prepared)
            return get_db_prep_value
        for field_class in args:
            field_class.get_db_prep_value = create_tweaked_get_db_prep_value(field_class.get_db_prep_value)

我在models.py文件的末尾激活它,像这样:

DBCurrentTimestamp.patch(models.DateField, models.TimeField, models.DateTimeField)

,并像这样使用:

self.last_pageview = DBCurrentTimestamp()

我已经创建了一个Python Django插件模块,它允许您在DateTimeField对象上控制CURRENT_TIMESTAMP的使用,无论是在特定情况下(参见下面的usage),还是自动用于auto_nowauto_now_add列。

django-pg-current-timestamp

GitHub: https://github.com/jaytaylor/django-pg-current-timestamp

PyPi: https://pypi.python.org/pypi/django-pg-current-timestamp

使用例子:

from django_pg_current_timestamp import CurrentTimestamp
mm = MyModel.objects.get(id=1)
mm.last_seen_date = CurrentTimestamp()
mm.save()
## Resulting SQL:
##     UPDATE "my_model" SET "last_seen_date" = CURRENT_TIMESTAMP;
print MyModel.objects.filter(last_seen_date__lt=CURRENT_TIME).count()
MyModel.objects.filter(id__in=[1, 2, 3]).update(last_seen_date=CURRENT_TIME)

如果你想从外部服务器(即不是Django应用程序的宿主服务器)获取日期时间,你将不得不手动绑定它以使用数据时间。您可以使用像select now();这样的SQL命令,或者像ssh user@host "date +%s"这样的SSH命令。

也许你应该看看文档:
Modelfields: DateField

选项'auto_now'可能正是您正在搜索的。您也可以将它与DateTimeField一起使用。它在每次保存模型时更新DateTime。因此,为DateTimeField设置该选项应该足以检索数据记录并再次保存以设置正确的时间。

创建表时,您想要创建的字段现在在字段中添加数据后将此代码添加到字段

class MyModel(models.Model):
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

最新更新