2018-02-23 16:23:22 +01:00
|
|
|
from django.db.models import CharField, Value
|
|
|
|
from django.db.models.functions import Left, Ord
|
|
|
|
from django.test import TestCase
|
2018-08-21 18:17:46 +02:00
|
|
|
from django.test.utils import register_lookup
|
2018-02-23 16:23:22 +01:00
|
|
|
|
2018-08-16 01:45:11 +02:00
|
|
|
from ..models import Author
|
2018-02-23 16:23:22 +01:00
|
|
|
|
|
|
|
|
|
|
|
class OrdTests(TestCase):
|
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
|
|
|
cls.john = Author.objects.create(name="John Smith", alias="smithj")
|
|
|
|
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena")
|
|
|
|
cls.rhonda = Author.objects.create(name="Rhonda")
|
|
|
|
|
|
|
|
def test_basic(self):
|
|
|
|
authors = Author.objects.annotate(name_part=Ord("name"))
|
|
|
|
self.assertCountEqual(
|
|
|
|
authors.filter(name_part__gt=Ord(Value("John"))), [self.elena, self.rhonda]
|
|
|
|
)
|
|
|
|
self.assertCountEqual(
|
|
|
|
authors.exclude(name_part__gt=Ord(Value("John"))), [self.john]
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_transform(self):
|
2018-08-21 18:17:46 +02:00
|
|
|
with register_lookup(CharField, Ord):
|
2018-02-23 16:23:22 +01:00
|
|
|
authors = Author.objects.annotate(first_initial=Left("name", 1))
|
|
|
|
self.assertCountEqual(
|
|
|
|
authors.filter(first_initial__ord=ord("J")), [self.john]
|
|
|
|
)
|
|
|
|
self.assertCountEqual(
|
|
|
|
authors.exclude(first_initial__ord=ord("J")), [self.elena, self.rhonda]
|
|
|
|
)
|