Refs #31640 -- Made Extract raise ValueError when using tzinfo with Date/TimeField.

This commit is contained in:
David-Wobrock 2020-10-05 17:39:53 +02:00 committed by Mariusz Felisiak
parent b26ec77deb
commit a0571c1003
2 changed files with 14 additions and 0 deletions

View File

@ -46,6 +46,8 @@ class Extract(TimezoneMixin, Transform):
if isinstance(lhs_output_field, DateTimeField):
tzname = self.get_tzname()
sql = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
elif self.tzinfo is not None:
raise ValueError('tzinfo can only be used with DateTimeField.')
elif isinstance(lhs_output_field, DateField):
sql = connection.ops.date_extract_sql(self.lookup_name, sql)
elif isinstance(lhs_output_field, TimeField):

View File

@ -1111,6 +1111,18 @@ class DateFunctionWithTimeZoneTests(DateFunctionTests):
self.assertEqual(model.day_melb, 16)
self.assertEqual(model.day_utc, 15)
def test_extract_invalid_field_with_timezone(self):
melb = pytz.timezone('Australia/Melbourne')
msg = 'tzinfo can only be used with DateTimeField.'
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.annotate(
day_melb=Extract('start_date', 'day', tzinfo=melb),
).get()
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.annotate(
hour_melb=Extract('start_time', 'hour', tzinfo=melb),
).get()
def test_trunc_timezone_applied_before_truncation(self):
start_datetime = datetime(2016, 1, 1, 1, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)