| 1 |
from django.db.models import CharField, Value |
| 2 |
from django.db.models.functions import Left, Ord |
| 3 |
from django.test import TestCase |
| 4 |
from django.test.utils import register_lookup |
| 5 |
|
| 6 |
from ..models import Author |
| 7 |
|
| 8 |
|
| 9 |
class OrdTests(TestCase): |
| 10 |
@classmethod |
| 11 |
def setUpTestData(cls): |
| 12 |
cls.john = Author.objects.create(name="John Smith", alias="smithj") |
| 13 |
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") |
| 14 |
cls.rhonda = Author.objects.create(name="Rhonda") |
| 15 |
|
| 16 |
def test_basic(self): |
| 17 |
authors = Author.objects.annotate(name_part=Ord("name")) |
| 18 |
self.assertCountEqual( |
| 19 |
authors.filter(name_part__gt=Ord(Value("John"))), [self.elena, self.rhonda] |
| 20 |
) |
| 21 |
self.assertCountEqual( |
| 22 |
authors.exclude(name_part__gt=Ord(Value("John"))), [self.john] |
| 23 |
) |
| 24 |
|
| 25 |
def test_transform(self): |
| 26 |
with register_lookup(CharField, Ord): |
| 27 |
authors = Author.objects.annotate(first_initial=Left("name", 1)) |
| 28 |
self.assertCountEqual( |
| 29 |
authors.filter(first_initial__ord=ord("J")), [self.john] |
| 30 |
) |
| 31 |
self.assertCountEqual( |
| 32 |
authors.exclude(first_initial__ord=ord("J")), [self.elena, self.rhonda] |
| 33 |
) |