From 4420761ea9457d386b2000cf9df5b2f6f88f8f91 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Tue, 19 Dec 2017 19:54:58 +0100 Subject: [PATCH] Fixed #28727 -- Fixed Cast crash on SQLite when casting a Python date/datetime to Date/DateTimeField. --- django/db/backends/sqlite3/operations.py | 4 ++++ tests/db_functions/test_cast.py | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py index a267d75ea4..61514a7642 100644 --- a/django/db/backends/sqlite3/operations.py +++ b/django/db/backends/sqlite3/operations.py @@ -14,6 +14,10 @@ from django.utils.duration import duration_string class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = 'text' + cast_data_types = { + 'DateField': 'TEXT', + 'DateTimeField': 'TEXT', + } def bulk_batch_size(self, fields, objs): """ diff --git a/tests/db_functions/test_cast.py b/tests/db_functions/test_cast.py index e266a13db1..6a6db9016d 100644 --- a/tests/db_functions/test_cast.py +++ b/tests/db_functions/test_cast.py @@ -1,4 +1,6 @@ -from django.db import models +import datetime + +from django.db import connection, models from django.db.models.expressions import Value from django.db.models.functions import Cast from django.test import TestCase, ignore_warnings, skipUnlessDBFeature @@ -42,6 +44,19 @@ class CastTests(TestCase): numbers = Author.objects.annotate(cast_int=Cast('alias', field_class())) self.assertEqual(numbers.get().cast_int, 1) + def test_cast_from_python_to_date(self): + today = datetime.date.today() + dates = Author.objects.annotate(cast_date=Cast(today, models.DateField())) + self.assertEqual(dates.get().cast_date, today) + + def test_cast_from_python_to_datetime(self): + now = datetime.datetime.now() + if connection.vendor == 'oracle': + # Workaround until #28934 is fixed. + now = now.replace(microsecond=0) + dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField())) + self.assertEqual(dates.get().cast_datetime, now) + def test_cast_from_python(self): numbers = Author.objects.annotate(cast_float=Cast(0, models.FloatField())) self.assertEqual(numbers.get().cast_float, 0.0)