Skip to content

Commit 0c589b4

Browse files
committed
BUG#34727432: Fix Django datetime error when USE_TZ=True in settings
When using the MySQL Connector/Python Django library as the backend in an application where time zone aware values are set to be used (USE_TZ=True), the `python migrate.py makemigrations` command fails with a ValueError exception because at some point Django assumes a given datetime value is naive and makes it zone aware. However, if the value is non-naive, an error is raised. With this patch, the issue is fixed by guaranteeing the DjangoMySQLConverter class returns naive datetime values. Change-Id: I9a46331d66b1bc865c4113c2caa0ec4d424abc1a
1 parent 95d740b commit 0c589b4

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

CHANGES.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ v8.0.32
1414
- WL#15348: Support MIT Kerberos library on Windows
1515
- WL#15036: Support for type hints
1616
- WL#14861: Remove distutils support
17+
- BUG#34727432: Fix Django datetime error when USE_TZ=True in settings
1718
- BUG#34710366: Django implementation does not pass unit tests
1819
- BUG#34695103: Remove debug messages that shows authentication data
1920
- BUG#34690501: Connector/Python depends on outdated protobuf

lib/mysql/connector/django/base.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -611,20 +611,19 @@ def _datetime_to_python(value: bytes, dsc: Any = None) -> Optional[datetime]:
611611
"""Connector/Python always returns naive datetime.datetime
612612
613613
Connector/Python always returns naive timestamps since MySQL has
614-
no time zone support. Since Django needs non-naive, we need to add
615-
the UTC time zone.
614+
no time zone support.
615+
616+
- A naive datetime is a datetime that doesn't know its own timezone.
617+
618+
Django needs a non-naive datetime, but in this method we don't need
619+
to make a datetime value time zone aware since Django itself at some
620+
point will make it aware (at least in versions 3.2.16 and 4.1.2) when
621+
USE_TZ=True. This may change in a future release, we need to keep an
622+
eye on this behaviour.
616623
617624
Returns datetime.datetime()
618625
"""
619-
if not value:
620-
return None
621-
622-
dt: Optional[datetime] = MySQLConverter._datetime_to_python(value)
623-
if dt is None:
624-
return None
625-
if settings.USE_TZ and timezone.is_naive(dt):
626-
dt = dt.replace(tzinfo=timezone.utc)
627-
return dt
626+
return MySQLConverter._datetime_to_python(value) if value else None
628627

629628
# pylint: enable=unused-argument
630629

0 commit comments

Comments
 (0)