2023-05-31 10:57:40 +00:00
|
|
|
from django.db import connection
|
2020-06-16 08:01:34 +00:00
|
|
|
from django.db.models import IntegerField, Value
|
2023-05-31 10:57:40 +00:00
|
|
|
from django.db.models.functions import Length, Lower, Right
|
2018-02-23 15:23:22 +00:00
|
|
|
from django.test import TestCase
|
|
|
|
|
2018-08-15 23:45:11 +00:00
|
|
|
from ..models import Author
|
2018-02-23 15:23:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class RightTests(TestCase):
|
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
|
|
|
Author.objects.create(name="John Smith", alias="smithj")
|
|
|
|
Author.objects.create(name="Rhonda")
|
|
|
|
|
|
|
|
def test_basic(self):
|
|
|
|
authors = Author.objects.annotate(name_part=Right("name", 5))
|
2022-09-24 10:29:58 +00:00
|
|
|
self.assertQuerySetEqual(
|
2018-02-23 15:23:22 +00:00
|
|
|
authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part
|
|
|
|
)
|
|
|
|
# If alias is null, set it to the first 2 lower characters of the name.
|
|
|
|
Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2)))
|
2022-09-24 10:29:58 +00:00
|
|
|
self.assertQuerySetEqual(
|
2018-02-23 15:23:22 +00:00
|
|
|
authors.order_by("name"), ["smithj", "da"], lambda a: a.alias
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_invalid_length(self):
|
|
|
|
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
|
|
|
|
Author.objects.annotate(raises=Right("name", 0))
|
|
|
|
|
2023-05-31 10:57:40 +00:00
|
|
|
def test_zero_length(self):
|
|
|
|
Author.objects.create(name="Tom", alias="tom")
|
|
|
|
authors = Author.objects.annotate(
|
|
|
|
name_part=Right("name", Length("name") - Length("alias"))
|
|
|
|
)
|
|
|
|
self.assertQuerySetEqual(
|
|
|
|
authors.order_by("name"),
|
|
|
|
[
|
|
|
|
"mith",
|
|
|
|
"" if connection.features.interprets_empty_strings_as_nulls else None,
|
|
|
|
"",
|
|
|
|
],
|
|
|
|
lambda a: a.name_part,
|
|
|
|
)
|
|
|
|
|
2018-02-23 15:23:22 +00:00
|
|
|
def test_expressions(self):
|
2020-06-16 08:01:34 +00:00
|
|
|
authors = Author.objects.annotate(
|
|
|
|
name_part=Right("name", Value(3, output_field=IntegerField()))
|
2018-02-23 15:23:22 +00:00
|
|
|
)
|
2022-09-24 10:29:58 +00:00
|
|
|
self.assertQuerySetEqual(
|
2018-02-23 15:23:22 +00:00
|
|
|
authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|