django设置DateTimeField为服务器当前时间[英] django set DateTimeField to server's current time

本文是小编为大家收集整理的关于django设置DateTimeField为服务器当前时间的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我如何在 django 中执行与此 SQL 等效的操作?

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

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

我知道您可以直接执行原始 sql,但我正在寻找更便携的解决方案,因为数据库具有不同的功能来获取当前日期时间.

编辑:很少有人提到 auto_now 参数.这会在每次修改时更新日期时间,而我只想在某些情况下更新日期时间.

推荐答案

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

或者如果你想手动做,不就是用python datetime.now()简单赋值吗?

from datetime import datetime

obj.date_modified = datetime.now()

本文地址:https://www.itbaoku.cn/post/597696.html

问题描述

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

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