Opened 3 weeks ago

Last modified 5 days ago

#37013 assigned Bug

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: Accepted
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 (8)

comment:1 by Jacob Walls, 3 weeks ago

Description: modified (diff)

comment:2 by Natalia Bidart, 3 weeks ago

Keywords: Extract Trunc added
Triage Stage: UnreviewedAccepted

Thank you! The forum post was very educational.

comment:3 by Huwaiza, 2 weeks ago

Cc: Huwaiza added
Owner: set to Huwaiza
Status: newassigned

comment:4 by Huwaiza, 2 weeks ago

Has patch: set

comment:5 by Jacob Walls, 2 weeks ago

Patch needs improvement: set

comment:6 by Huwaiza, 9 days ago

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

comment:7 by Tim Graham, 9 days 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, 5 days ago

Sure, thanks.

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