Opened 6 months ago

Closed 4 weeks ago

#37013 closed Bug (fixed)

Omitting tzinfo argument to Trunc & Extract with USE_TZ = True and TIME_ZONE != UTC creates ambiguity for migrations

Reported by: Jacob Walls Owned by: Huwaiza
Component: Database layer (models, ORM) Version: 6.0
Severity: Normal Keywords: tzinfo, TIME_ZONE, Extract, Trunc
Cc: Huwaiza Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Jacob Walls)

The Trunc() and Extract() database functions apply timezone conversions if USE_TZ = True. When the tzinfo argument is omitted, the timezone is inferred from settings.TIME_ZONE. If these functions are used in a db_default expression, this information is not captured by migrations, meaning that if settings.TIME_ZONE changes over the life of a project, then the database may never receive a corresponding update.

from django.db import models
from django.db.models.functions import ExtractHour, Now

class Person(models.Model):
    hour = models.IntegerField(db_default=ExtractHour(Now()))

To reproduce:

  • Change settings.TIME_ZONE to "America/Chicago".
  • Make migrations, notice no migration generated.
  • Emulating the database-default python-side (as SQLite must do sometimes, see rest of linked forum post) now no longer produces the same value as the database.

In this ​forum reply, there was an idea to implement Trunc/Extract.deconstruct() to deprecate omitting tzinfo if serialized into a migration and eventually make it default to get_current_timezone() when not provided.

Change History (12)

comment:1 by Jacob Walls, 6 months ago

Description: modified (diff)

comment:2 by Natalia Bidart, 6 months ago

Keywords: Extract Trunc added
Triage Stage: Unreviewed → Accepted

Thank you! The forum post was very educational.

comment:3 by Huwaiza, 6 months ago

Cc: Huwaiza added
Owner: set to Huwaiza
Status: new → assigned

comment:4 by Huwaiza, 6 months ago

Has patch: set

comment:5 by Jacob Walls, 6 months ago

Patch needs improvement: set

comment:6 by Huwaiza, 6 months ago

Hi Jacob, all comments on the PR have been addressed, can you pease review, thanks.

comment:7 by Tim Graham, 6 months ago

Patch needs improvement: unset

In the future, please uncheck "Patch needs improvement" to return the ticket to the review queue.

comment:8 by Huwaiza, 6 months ago

Sure, thanks.

comment:9 by Jacob Walls, 4 months ago

Patch needs improvement: set

comment:10 by Huwaiza, 3 months ago

Patch needs improvement: unset

comment:11 by Jacob Walls, 4 weeks ago

Triage Stage: Accepted → Ready for checkin

comment:12 by GitHub <noreply@…>, 4 weeks ago

Resolution: → fixed
Status: assigned → closed

In b3f4d83:

Fixed #37013 -- Deprecated Trunc/Extract in migrations with USE_TZ=True and no tzinfo.

In Django 2029, the current timezone will be stored in the migration.

Note: See TracTickets for help on using tickets.
Back to Top