Django DateTime字段,用于生成带时区的时间戳记字段 [英] Django DateTime field to generate timestamp fields withOUT timezone

查看:303
本文介绍了Django DateTime字段,用于生成带时区的时间戳记字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个Django应用程序,我需要所有postgres代表的datetime字段保存在UTC(应该)。当我使用DateTime字段创建模型时,它们的数据库表示生成为时间戳与时区
虽然我可以手动修改表以从字段中删除时区,但我想知道DateTime模型字段是否有能力不这样做 - 即创建带有时区的时间戳某些领域。
这是可能的吗?还是我必须改变他们的表?
谢谢,
Harel

解决方案

Django中postgres的数据类型映射到字符串文字时间戳与时区,似乎没有更改该类型的选项。



就我而言'知道,你有三个选择:


  1. 利用Django的钩子执行 create sql之后的create table语句。为此,您可以在应用程序中创建一个名为 sql 的目录,该目录中名为 mymodel.postgres_psycopg2.sql 的文件。将你的alter table语句放在那里。


  2. 编写一个自定义字段来定义你认为合适的时间戳字段的修饰符。请参阅编写自定义模型字段


  3. 保留django字段,并在应用程序中执行时区转换,以确保您正确传递正确的时间。


我个人对数据完整性的偏好是#3。与字符编码一样,您始终希望确定您知道字符集并正确处理转换,对于其属性(包括TZ)的属性(包括TZ)的精确定义,我感到更加舒适。您可能今​​天肯定您的所有输入都已经以UTC为准,但这可能会改变,特别是如果时间戳由最终用户提供。对于什么值得,我会去额外的一英里,将应用程序中的时间戳转换为UTC,并将其存储在数据库中,UTC为时区。


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

解决方案

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:

  1. 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 called mymodel.postgres_psycopg2.sql. Place your alter table statements in there.

  2. Write a custom field to define the modifiers for the timestamp field as you see fit. See "writing custom model fields".

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

这篇关于Django DateTime字段,用于生成带时区的时间戳记字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆