| 1 |
from django.db.models import IntegerField, Value |
| 2 |
from django.db.models.functions import Left, Lower |
| 3 |
from django.test import TestCase |
| 4 |
|
| 5 |
from ..models import Author |
| 6 |
|
| 7 |
|
| 8 |
class LeftTests(TestCase): |
| 9 |
@classmethod |
| 10 |
def setUpTestData(cls): |
| 11 |
Author.objects.create(name="John Smith", alias="smithj") |
| 12 |
Author.objects.create(name="Rhonda") |
| 13 |
|
| 14 |
def test_basic(self): |
| 15 |
authors = Author.objects.annotate(name_part=Left("name", 5)) |
| 16 |
self.assertQuerySetEqual( |
| 17 |
authors.order_by("name"), ["John ", "Rhond"], lambda a: a.name_part |
| 18 |
) |
| 19 |
# If alias is null, set it to the first 2 lower characters of the name. |
| 20 |
Author.objects.filter(alias__isnull=True).update(alias=Lower(Left("name", 2))) |
| 21 |
self.assertQuerySetEqual( |
| 22 |
authors.order_by("name"), ["smithj", "rh"], lambda a: a.alias |
| 23 |
) |
| 24 |
|
| 25 |
def test_invalid_length(self): |
| 26 |
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): |
| 27 |
Author.objects.annotate(raises=Left("name", 0)) |
| 28 |
|
| 29 |
def test_expressions(self): |
| 30 |
authors = Author.objects.annotate( |
| 31 |
name_part=Left("name", Value(3, output_field=IntegerField())) |
| 32 |
) |
| 33 |
self.assertQuerySetEqual( |
| 34 |
authors.order_by("name"), ["Joh", "Rho"], lambda a: a.name_part |
| 35 |
) |