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