Opened 2 hours ago

Last modified 112 minutes ago

#37013 new 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:
Component: Database layer (models, ORM) Version: 6.0
Severity: Normal Keywords: tzinfo, TIME_ZONE, Extract, Trunc
Cc: Triage Stage: Accepted
Has patch: no 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 (2)

comment:1 by Jacob Walls, 2 hours ago

Description: modified (diff)

comment:2 by Natalia Bidart, 112 minutes ago

Keywords: Extract Trunc added
Triage Stage: UnreviewedAccepted

Thank you! The forum post was very educational.

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