Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
A fix to remove timezone information from dates before inserting in t…
…he DB.


Some DBs do not support timezones on dates (notably, MySQL). We therefore have to remove the timezone information before storing the value. This is not too bad as we convert to the default timezone in `get_db_prep_save()`, and add the default timezone information back in `get_db_prep_lookup()`.

I have tried to code this in a way that will be both backwards compatible (no `connection` parameter in Django < 1.3) and not hard-wired to MySQL specifically.

Of course, if the user changes the default timezone while there is data in the database, it will cause the dates in the database to skew. This is not ideal, but there is not much we can do about this apart from either forcing all dates to be stored in UTC, or putting a suitably large warning somewhere in the docs.

For my part, I wouldn't not mind forcing to UTC, but I am in the UK, so the impact of that for me is probably going to be less.
  • Loading branch information
Adam Charnock committed Sep 15, 2011
1 parent ce12f45 commit 5ce210f
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions timezones/fields.py
Expand Up @@ -104,6 +104,15 @@ def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=None)
value = default_tz.localize(value)
else:
value = value.astimezone(default_tz)

# Make sure the DB can handle timezone-aware dates (hint: MySQL cannot)
if connection and getattr(connection, "ops") and getattr(connection.ops, "value_to_db_datetime"):
try:
connection.ops.value_to_db_datetime(value)
except ValueError:
# DB doesn't support timezones, so strip it off
value = value.replace(tzinfo=None)

return super(LocalizedDateTimeField, self).get_db_prep_lookup(lookup_type, value, connection=connection, prepared=prepared)


Expand Down

0 comments on commit 5ce210f

Please sign in to comment.