| 1 |
from django.db.models import Value as V |
| 2 |
from django.db.models.functions import Lower, StrIndex, Substr, Upper |
| 3 |
from django.test import TestCase |
| 4 |
|
| 5 |
from ..models import Author |
| 6 |
|
| 7 |
|
| 8 |
class SubstrTests(TestCase): |
| 9 |
def test_basic(self): |
| 10 |
Author.objects.create(name="John Smith", alias="smithj") |
| 11 |
Author.objects.create(name="Rhonda") |
| 12 |
authors = Author.objects.annotate(name_part=Substr("name", 5, 3)) |
| 13 |
self.assertQuerySetEqual( |
| 14 |
authors.order_by("name"), [" Sm", "da"], lambda a: a.name_part |
| 15 |
) |
| 16 |
authors = Author.objects.annotate(name_part=Substr("name", 2)) |
| 17 |
self.assertQuerySetEqual( |
| 18 |
authors.order_by("name"), ["ohn Smith", "honda"], lambda a: a.name_part |
| 19 |
) |
| 20 |
# If alias is null, set to first 5 lower characters of the name. |
| 21 |
Author.objects.filter(alias__isnull=True).update( |
| 22 |
alias=Lower(Substr("name", 1, 5)), |
| 23 |
) |
| 24 |
self.assertQuerySetEqual( |
| 25 |
authors.order_by("name"), ["smithj", "rhond"], lambda a: a.alias |
| 26 |
) |
| 27 |
|
| 28 |
def test_start(self): |
| 29 |
Author.objects.create(name="John Smith", alias="smithj") |
| 30 |
a = Author.objects.annotate( |
| 31 |
name_part_1=Substr("name", 1), |
| 32 |
name_part_2=Substr("name", 2), |
| 33 |
).get(alias="smithj") |
| 34 |
|
| 35 |
self.assertEqual(a.name_part_1[1:], a.name_part_2) |
| 36 |
|
| 37 |
def test_pos_gt_zero(self): |
| 38 |
with self.assertRaisesMessage(ValueError, "'pos' must be greater than 0"): |
| 39 |
Author.objects.annotate(raises=Substr("name", 0)) |
| 40 |
|
| 41 |
def test_expressions(self): |
| 42 |
Author.objects.create(name="John Smith", alias="smithj") |
| 43 |
Author.objects.create(name="Rhonda") |
| 44 |
substr = Substr(Upper("name"), StrIndex("name", V("h")), 5) |
| 45 |
authors = Author.objects.annotate(name_part=substr) |
| 46 |
self.assertQuerySetEqual( |
| 47 |
authors.order_by("name"), ["HN SM", "HONDA"], lambda a: a.name_part |
| 48 |
) |