Django DateTime 字段生成不带时区的时间戳字段
我正在开发一个 Django 应用程序,我需要将所有 postgres 表示的日期时间字段保存在 UTC 中(因为它们应该如此)。当我使用 DateTime 字段创建模型时,它们的数据库表示形式生成为“带时区的时间戳”。 虽然我可以手动更改表以从字段中删除时区,但我想知道 DateTime 模型字段是否有能力不这样做 - 即,为某些创建“没有时区的时间戳”字段。 这可能吗?或者我必须改变它们的表吗? 谢谢, 哈雷尔
I am working on a Django application where I need all the postgres represented datetime fields to be saved in UTC (as they should). When I'm creating models with DateTime fields they database representation is generated as "timestamp with time zone".
Although I can manually alter the tables to remove the timezone from the fields, I was wondering if the DateTime model field has the ability to not do that - i.e., create "timestamp with out time zone" for some fields.
Is that possible? Or do I have to alter them tables?
Thanks,
Harel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Django 中 postgres 的数据类型映射到字符串文字
timestamp with time zone
,并且似乎没有可以更改该类型的选项。据我所知,您有三个选择:
利用 Django 的钩子来执行 建表语句后的原始sql。为此,请在您的应用中创建一个名为
sql
的目录,并在该目录中创建一个名为mymodel.postgres_psycopg2.sql
的文件。将您的 alter table 语句放在那里。编写一个自定义字段来定义您认为合适的时间戳字段的修饰符。请参阅“编写自定义模型字段< /a>”。
保留 django 字段不变,并在您的应用程序中执行时区转换,以便您绝对确定您传递的是正确的时间。
保留 django 字段不变
我个人对数据完整性的偏好是#3。就像字符编码一样,您总是希望确保了解字符集并正确处理转换,我对属性(包括 TZ)尽可能精确定义的日期/时间感到更舒服。今天您可能确定所有输入都已以 UTC 格式传入您的应用程序,但这可能会发生变化,特别是如果时间戳由最终用户提供的话。不管怎样,我会加倍努力,将应用程序中的时间戳转换为 UTC,并将其存储在数据库中,并以 UTC 作为时区。
The data types for postgres in Django map to the string literal
timestamp with time zone
, and there doesn't seem to be an option to alter that type.As far as I'm aware, you have three options:
Take advantage of Django's hook for executing raw sql after the create table statement. To do this create a directory called
sql
in your app and a file in that directory calledmymodel.postgres_psycopg2.sql
. Place your alter table statements in there.Write a custom field to define the modifiers for the timestamp field as you see fit. See "writing custom model fields".
Leave the django field as is, and perform the timezone conversion in your application so that you are absolutely certain you are passing the correct time.
My personal preference for data integrity is #3. Just as with character encodings, where you always want to be sure you know the charset and are handling conversions properly, I feel much more comfortable with dates/times whose attributes (including TZ) are as precisely defined as they can be. You may be certain today that all your input is coming to your app already in UTC, but that may change, particular if the timestamps are supplied by end users. For what it's worth, I'd go the extra mile, convert the timestamp in the app to UTC, and store it in the DB with UTC as the time zone.