Opened 9 years ago

Closed 8 years ago

#26348 closed New feature (fixed)

Add a __time lookup for DateTimeField

Reported by: Simon Charette Owned by: Simon Charette
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: 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

Now that we've added the __date (#9596) lookup I think we should allow the same for the time part.

A good usage example would be:

Event.objects.filter(
    datetime__time__range=(start_time, end_time),
)

To select all activities that occurred in a timezone aware time range.

Here's an implementation for PostgreSQL and MySQL missing tests:

from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property


class DateTimeTimeTransform(models.Transform):
    lookup_name = 'time'

    @cached_property
    def output_field(self):
        return models.TimeField()

    def as_mysql(self, compiler, connection):
        lhs, lhs_params = compiler.compile(self.lhs)
        if settings.USE_TZ:
            lhs = "CONVERT_TZ(%s, 'UTC', %%s)" % lhs
            tzname = timezone.get_current_timezone_name()
            lhs_params.append(tzname)
        sql = "TIME(%s)" % lhs
        return sql, lhs_params

    def as_postgresql(self, compiler, connection):
        lhs, lhs_params = compiler.compile(self.lhs)
        if settings.USE_TZ:
            lhs = "%s AT TIME ZONE %%s" % lhs
            tzname = timezone.get_current_timezone_name()
            lhs_params.append(tzname)
        sql = "(%s)::time" % lhs
        return sql, lhs_params

models.DateTimeField.register_lookup(DateTimeTimeTransform)

We should wait for the datetime expression refactor (#25774) to land before proceeding with this patch.

Change History (8)

comment:1 by Tim Graham, 9 years ago

Triage Stage: UnreviewedAccepted

comment:2 by Simon Charette, 9 years ago

Owner: changed from nobody to Simon Charette
Status: newassigned

comment:3 by Simon Charette, 9 years ago

Has patch: set

PR with missing Oracle support.

comment:4 by Tim Graham, 8 years ago

Patch needs improvement: set

Left a few comments for improvement on the PR.

comment:5 by Simon Charette, 8 years ago

Patch needs improvement: unset

comment:6 by Tim Graham, 8 years ago

Triage Stage: AcceptedReady for checkin

comment:7 by Simon Charette <charette.s@…>, 8 years ago

In 082c52db:

Refs #25774, #26348 -- Allowed Trunc functions to operate with time fields.

Thanks Josh for the amazing testing setup and Tim for the review.

comment:8 by Simon Charette <charette.s@…>, 8 years ago

Resolution: fixed
Status: assignedclosed

In 8a4f017f:

Fixed #26348 -- Added TruncTime and exposed it through the time lookup.

Thanks Tim for the review.

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