2020-06-16 16:01:34 +08:00
|
|
|
from django.db.models import IntegerField, Value
|
2018-02-23 23:23:22 +08:00
|
|
|
from django.db.models.functions import Left, Lower
|
|
|
|
from django.test import TestCase
|
|
|
|
|
2018-08-16 07:45:11 +08:00
|
|
|
from ..models import Author
|
2018-02-23 23:23:22 +08:00
|
|
|
|
|
|
|
|
|
|
|
class LeftTests(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=Left("name", 5))
|
2022-09-24 18:29:58 +08:00
|
|
|
self.assertQuerySetEqual(
|
2018-02-23 23:23:22 +08:00
|
|
|
authors.order_by("name"), ["John ", "Rhond"], 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(Left("name", 2)))
|
2022-09-24 18:29:58 +08:00
|
|
|
self.assertQuerySetEqual(
|
2018-02-23 23:23:22 +08:00
|
|
|
authors.order_by("name"), ["smithj", "rh"], lambda a: a.alias
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_invalid_length(self):
|
|
|
|
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
|
|
|
|
Author.objects.annotate(raises=Left("name", 0))
|
|
|
|
|
|
|
|
def test_expressions(self):
|
2020-06-16 16:01:34 +08:00
|
|
|
authors = Author.objects.annotate(
|
|
|
|
name_part=Left("name", Value(3, output_field=IntegerField()))
|
2018-02-23 23:23:22 +08:00
|
|
|
)
|
2022-09-24 18:29:58 +08:00
|
|
|
self.assertQuerySetEqual(
|
2018-02-23 23:23:22 +08:00
|
|
|
authors.order_by("name"), ["Joh", "Rho"], lambda a: a.name_part
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|