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

This commit is contained in:
Hasan Ramezani 2019-07-11 21:13:36 +02:00 committed by Mariusz Felisiak
parent 7a42cfcfdc
commit 402e6d292f
2 changed files with 15 additions and 0 deletions

View File

@ -73,6 +73,14 @@ class Extract(TimezoneMixin, Transform):
raise ValueError(
"Cannot extract time component '%s' from DateField '%s'. " % (copy.lookup_name, field.name)
)
if (
isinstance(field, DurationField) and
copy.lookup_name in ('year', 'iso_year', 'month', 'week', 'week_day', 'quarter')
):
raise ValueError(
"Cannot extract component '%s' from DurationField '%s'."
% (copy.lookup_name, field.name)
)
return copy

View File

@ -273,6 +273,13 @@ class DateFunctionTests(TestCase):
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(extracted=Extract('duration', 'second')))
def test_extract_duration_unsupported_lookups(self):
msg = "Cannot extract component '%s' from DurationField 'duration'."
for lookup in ('year', 'iso_year', 'month', 'week', 'week_day', 'quarter'):
with self.subTest(lookup):
with self.assertRaisesMessage(ValueError, msg % lookup):
DTModel.objects.annotate(extracted=Extract('duration', lookup))
def test_extract_year_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)