| 1 |
from django.db.models import CharField |
| 2 |
from django.db.models.functions import Length |
| 3 |
from django.test import TestCase |
| 4 |
from django.test.utils import register_lookup |
| 5 |
|
| 6 |
from ..models import Author |
| 7 |
|
| 8 |
|
| 9 |
class LengthTests(TestCase): |
| 10 |
def test_basic(self): |
| 11 |
Author.objects.create(name="John Smith", alias="smithj") |
| 12 |
Author.objects.create(name="Rhonda") |
| 13 |
authors = Author.objects.annotate( |
| 14 |
name_length=Length("name"), |
| 15 |
alias_length=Length("alias"), |
| 16 |
) |
| 17 |
self.assertQuerySetEqual( |
| 18 |
authors.order_by("name"), |
| 19 |
[(10, 6), (6, None)], |
| 20 |
lambda a: (a.name_length, a.alias_length), |
| 21 |
) |
| 22 |
self.assertEqual(authors.filter(alias_length__lte=Length("name")).count(), 1) |
| 23 |
|
| 24 |
def test_ordering(self): |
| 25 |
Author.objects.create(name="John Smith", alias="smithj") |
| 26 |
Author.objects.create(name="John Smith", alias="smithj1") |
| 27 |
Author.objects.create(name="Rhonda", alias="ronny") |
| 28 |
authors = Author.objects.order_by(Length("name"), Length("alias")) |
| 29 |
self.assertQuerySetEqual( |
| 30 |
authors, |
| 31 |
[ |
| 32 |
("Rhonda", "ronny"), |
| 33 |
("John Smith", "smithj"), |
| 34 |
("John Smith", "smithj1"), |
| 35 |
], |
| 36 |
lambda a: (a.name, a.alias), |
| 37 |
) |
| 38 |
|
| 39 |
def test_transform(self): |
| 40 |
with register_lookup(CharField, Length): |
| 41 |
Author.objects.create(name="John Smith", alias="smithj") |
| 42 |
Author.objects.create(name="Rhonda") |
| 43 |
authors = Author.objects.filter(name__length__gt=7) |
| 44 |
self.assertQuerySetEqual( |
| 45 |
authors.order_by("name"), ["John Smith"], lambda a: a.name |
| 46 |
) |