Opened 5 years ago

Closed 5 years ago

#30602 closed Cleanup/optimization (fixed)

Raise ValueError in Extract lookups that don't work properly with DurationField.

Reported by: cecedille1 Owned by: Hasan Ramezani
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

Lookups on ExtractYear on a DurationField fails because ExtractYear has an optimisation where it compares the source date with a range of dates.

class MyModel(models.Model):
    duration = models.DurationField()

MyModel.objects.annotate(year=ExtractYear('duration')).filter(year__gt=1)

The queryset generated looks like

SELECT * FROM mymodel WHERE duration > '0001-01-01'

and it fails because interval are not comparable with dates

Change History (7)

comment:1 by Simon Charette, 5 years ago

As I mentioned on the PR Extract functions don't explicitly support DurationField; it's not documented nor tested. They happen to work for PostgreSQL because EXTRACT(component FROM ::interval) happens to work but that's just a coincidence.

I'm not sure if this ticket should be closed as invalid or repurposed as a feature request to add tested support. We'll have to come with with a way of defining units such as years though, do we want to consider them as 365.25 days?

Last edited 5 years ago by Simon Charette (previous) (diff)

comment:2 by Mariusz Felisiak, 5 years ago

Summary: ExtractYear lookups on a DurationField failsExtractYear lookups crash on a DurationField.
Triage Stage: UnreviewedAccepted
Version: 2.2master

Support for DurationField to Extract was added in #27473, so it is a bug (see comment).

comment:3 by Mariusz Felisiak, 5 years ago

Has patch: set
Owner: changed from nobody to cecedille1
Status: newassigned

comment:4 by Mariusz Felisiak, 5 years ago

Has patch: unset
Summary: ExtractYear lookups crash on a DurationField.Raise ValueError in Extract lookups that don't work properly with DurationField.

DurationField is modeled in Python by timedelta (see documentation), so even with this fix it will always return 0 for ExtractYear, ExtractMonth, or ExtractWeek which is unexpected. We should raise ValueError in all such cases.

comment:5 by Hasan Ramezani, 5 years ago

Has patch: set
Owner: changed from cecedille1 to Hasan Ramezani
Last edited 5 years ago by Mariusz Felisiak (previous) (diff)

comment:6 by Mariusz Felisiak, 5 years ago

Easy pickings: set
Type: BugCleanup/optimization

comment:7 by Mariusz Felisiak <felisiak.mariusz@…>, 5 years ago

Resolution: fixed
Status: assignedclosed

In 402e6d29:

Fixed #30602 -- Made Extract raise ValueError when using unsupported lookups for DurationField.

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