1. import datetime
    
  2. import decimal
    
  3. import unittest
    
  4. 
    
  5. from django.db import connection, models
    
  6. from django.db.models.functions import Cast
    
  7. from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
    
  8. from django.test.utils import CaptureQueriesContext
    
  9. 
    
  10. from ..models import Author, DTModel, Fan, FloatModel
    
  11. 
    
  12. 
    
  13. class CastTests(TestCase):
    
  14.     @classmethod
    
  15.     def setUpTestData(self):
    
  16.         Author.objects.create(name="Bob", age=1, alias="1")
    
  17. 
    
  18.     def test_cast_from_value(self):
    
  19.         numbers = Author.objects.annotate(
    
  20.             cast_integer=Cast(models.Value("0"), models.IntegerField())
    
  21.         )
    
  22.         self.assertEqual(numbers.get().cast_integer, 0)
    
  23. 
    
  24.     def test_cast_from_field(self):
    
  25.         numbers = Author.objects.annotate(
    
  26.             cast_string=Cast("age", models.CharField(max_length=255)),
    
  27.         )
    
  28.         self.assertEqual(numbers.get().cast_string, "1")
    
  29. 
    
  30.     def test_cast_to_char_field_without_max_length(self):
    
  31.         numbers = Author.objects.annotate(cast_string=Cast("age", models.CharField()))
    
  32.         self.assertEqual(numbers.get().cast_string, "1")
    
  33. 
    
  34.     # Silence "Truncated incorrect CHAR(1) value: 'Bob'".
    
  35.     @ignore_warnings(module="django.db.backends.mysql.base")
    
  36.     @skipUnlessDBFeature("supports_cast_with_precision")
    
  37.     def test_cast_to_char_field_with_max_length(self):
    
  38.         names = Author.objects.annotate(
    
  39.             cast_string=Cast("name", models.CharField(max_length=1))
    
  40.         )
    
  41.         self.assertEqual(names.get().cast_string, "B")
    
  42. 
    
  43.     @skipUnlessDBFeature("supports_cast_with_precision")
    
  44.     def test_cast_to_decimal_field(self):
    
  45.         FloatModel.objects.create(f1=-1.934, f2=3.467)
    
  46.         float_obj = FloatModel.objects.annotate(
    
  47.             cast_f1_decimal=Cast(
    
  48.                 "f1", models.DecimalField(max_digits=8, decimal_places=2)
    
  49.             ),
    
  50.             cast_f2_decimal=Cast(
    
  51.                 "f2", models.DecimalField(max_digits=8, decimal_places=1)
    
  52.             ),
    
  53.         ).get()
    
  54.         self.assertEqual(float_obj.cast_f1_decimal, decimal.Decimal("-1.93"))
    
  55.         self.assertEqual(float_obj.cast_f2_decimal, decimal.Decimal("3.5"))
    
  56.         author_obj = Author.objects.annotate(
    
  57.             cast_alias_decimal=Cast(
    
  58.                 "alias", models.DecimalField(max_digits=8, decimal_places=2)
    
  59.             ),
    
  60.         ).get()
    
  61.         self.assertEqual(author_obj.cast_alias_decimal, decimal.Decimal("1"))
    
  62. 
    
  63.     def test_cast_to_integer(self):
    
  64.         for field_class in (
    
  65.             models.AutoField,
    
  66.             models.BigAutoField,
    
  67.             models.SmallAutoField,
    
  68.             models.IntegerField,
    
  69.             models.BigIntegerField,
    
  70.             models.SmallIntegerField,
    
  71.             models.PositiveBigIntegerField,
    
  72.             models.PositiveIntegerField,
    
  73.             models.PositiveSmallIntegerField,
    
  74.         ):
    
  75.             with self.subTest(field_class=field_class):
    
  76.                 numbers = Author.objects.annotate(cast_int=Cast("alias", field_class()))
    
  77.                 self.assertEqual(numbers.get().cast_int, 1)
    
  78. 
    
  79.     def test_cast_to_duration(self):
    
  80.         duration = datetime.timedelta(days=1, seconds=2, microseconds=3)
    
  81.         DTModel.objects.create(duration=duration)
    
  82.         dtm = DTModel.objects.annotate(
    
  83.             cast_duration=Cast("duration", models.DurationField()),
    
  84.             cast_neg_duration=Cast(-duration, models.DurationField()),
    
  85.         ).get()
    
  86.         self.assertEqual(dtm.cast_duration, duration)
    
  87.         self.assertEqual(dtm.cast_neg_duration, -duration)
    
  88. 
    
  89.     def test_cast_from_db_datetime_to_date(self):
    
  90.         dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567)
    
  91.         DTModel.objects.create(start_datetime=dt_value)
    
  92.         dtm = DTModel.objects.annotate(
    
  93.             start_datetime_as_date=Cast("start_datetime", models.DateField())
    
  94.         ).first()
    
  95.         self.assertEqual(dtm.start_datetime_as_date, datetime.date(2018, 9, 28))
    
  96. 
    
  97.     def test_cast_from_db_datetime_to_time(self):
    
  98.         dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567)
    
  99.         DTModel.objects.create(start_datetime=dt_value)
    
  100.         dtm = DTModel.objects.annotate(
    
  101.             start_datetime_as_time=Cast("start_datetime", models.TimeField())
    
  102.         ).first()
    
  103.         rounded_ms = int(
    
  104.             round(0.234567, connection.features.time_cast_precision) * 10**6
    
  105.         )
    
  106.         self.assertEqual(
    
  107.             dtm.start_datetime_as_time, datetime.time(12, 42, 10, rounded_ms)
    
  108.         )
    
  109. 
    
  110.     def test_cast_from_db_date_to_datetime(self):
    
  111.         dt_value = datetime.date(2018, 9, 28)
    
  112.         DTModel.objects.create(start_date=dt_value)
    
  113.         dtm = DTModel.objects.annotate(
    
  114.             start_as_datetime=Cast("start_date", models.DateTimeField())
    
  115.         ).first()
    
  116.         self.assertEqual(
    
  117.             dtm.start_as_datetime, datetime.datetime(2018, 9, 28, 0, 0, 0, 0)
    
  118.         )
    
  119. 
    
  120.     def test_cast_from_db_datetime_to_date_group_by(self):
    
  121.         author = Author.objects.create(name="John Smith", age=45)
    
  122.         dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567)
    
  123.         Fan.objects.create(name="Margaret", age=50, author=author, fan_since=dt_value)
    
  124.         fans = (
    
  125.             Fan.objects.values("author")
    
  126.             .annotate(
    
  127.                 fan_for_day=Cast("fan_since", models.DateField()),
    
  128.                 fans=models.Count("*"),
    
  129.             )
    
  130.             .values()
    
  131.         )
    
  132.         self.assertEqual(fans[0]["fan_for_day"], datetime.date(2018, 9, 28))
    
  133.         self.assertEqual(fans[0]["fans"], 1)
    
  134. 
    
  135.     def test_cast_from_python_to_date(self):
    
  136.         today = datetime.date.today()
    
  137.         dates = Author.objects.annotate(cast_date=Cast(today, models.DateField()))
    
  138.         self.assertEqual(dates.get().cast_date, today)
    
  139. 
    
  140.     def test_cast_from_python_to_datetime(self):
    
  141.         now = datetime.datetime.now()
    
  142.         dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField()))
    
  143.         time_precision = datetime.timedelta(
    
  144.             microseconds=10 ** (6 - connection.features.time_cast_precision)
    
  145.         )
    
  146.         self.assertAlmostEqual(dates.get().cast_datetime, now, delta=time_precision)
    
  147. 
    
  148.     def test_cast_from_python(self):
    
  149.         numbers = Author.objects.annotate(
    
  150.             cast_float=Cast(decimal.Decimal(0.125), models.FloatField())
    
  151.         )
    
  152.         cast_float = numbers.get().cast_float
    
  153.         self.assertIsInstance(cast_float, float)
    
  154.         self.assertEqual(cast_float, 0.125)
    
  155. 
    
  156.     @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL test")
    
  157.     def test_expression_wrapped_with_parentheses_on_postgresql(self):
    
  158.         """
    
  159.         The SQL for the Cast expression is wrapped with parentheses in case
    
  160.         it's a complex expression.
    
  161.         """
    
  162.         with CaptureQueriesContext(connection) as captured_queries:
    
  163.             list(
    
  164.                 Author.objects.annotate(
    
  165.                     cast_float=Cast(models.Avg("age"), models.FloatField()),
    
  166.                 )
    
  167.             )
    
  168.         self.assertIn(
    
  169.             '(AVG("db_functions_author"."age"))::double precision',
    
  170.             captured_queries[0]["sql"],
    
  171.         )
    
  172. 
    
  173.     def test_cast_to_text_field(self):
    
  174.         self.assertEqual(
    
  175.             Author.objects.values_list(
    
  176.                 Cast("age", models.TextField()), flat=True
    
  177.             ).get(),
    
  178.             "1",
    
  179.         )