| 1 |
from django.db.models import CharField |
| 2 |
from django.db.models import Value as V |
| 3 |
from django.db.models.functions import Coalesce, Length, Upper |
| 4 |
from django.test import TestCase |
| 5 |
from django.test.utils import register_lookup |
| 6 |
|
| 7 |
from .models import Author |
| 8 |
|
| 9 |
|
| 10 |
class UpperBilateral(Upper): |
| 11 |
bilateral = True |
| 12 |
|
| 13 |
|
| 14 |
class FunctionTests(TestCase): |
| 15 |
def test_nested_function_ordering(self): |
| 16 |
Author.objects.create(name="John Smith") |
| 17 |
Author.objects.create(name="Rhonda Simpson", alias="ronny") |
| 18 |
|
| 19 |
authors = Author.objects.order_by(Length(Coalesce("alias", "name"))) |
| 20 |
self.assertQuerySetEqual( |
| 21 |
authors, |
| 22 |
[ |
| 23 |
"Rhonda Simpson", |
| 24 |
"John Smith", |
| 25 |
], |
| 26 |
lambda a: a.name, |
| 27 |
) |
| 28 |
|
| 29 |
authors = Author.objects.order_by(Length(Coalesce("alias", "name")).desc()) |
| 30 |
self.assertQuerySetEqual( |
| 31 |
authors, |
| 32 |
[ |
| 33 |
"John Smith", |
| 34 |
"Rhonda Simpson", |
| 35 |
], |
| 36 |
lambda a: a.name, |
| 37 |
) |
| 38 |
|
| 39 |
def test_func_transform_bilateral(self): |
| 40 |
with register_lookup(CharField, UpperBilateral): |
| 41 |
Author.objects.create(name="John Smith", alias="smithj") |
| 42 |
Author.objects.create(name="Rhonda") |
| 43 |
authors = Author.objects.filter(name__upper__exact="john smith") |
| 44 |
self.assertQuerySetEqual( |
| 45 |
authors.order_by("name"), |
| 46 |
[ |
| 47 |
"John Smith", |
| 48 |
], |
| 49 |
lambda a: a.name, |
| 50 |
) |
| 51 |
|
| 52 |
def test_func_transform_bilateral_multivalue(self): |
| 53 |
with register_lookup(CharField, UpperBilateral): |
| 54 |
Author.objects.create(name="John Smith", alias="smithj") |
| 55 |
Author.objects.create(name="Rhonda") |
| 56 |
authors = Author.objects.filter(name__upper__in=["john smith", "rhonda"]) |
| 57 |
self.assertQuerySetEqual( |
| 58 |
authors.order_by("name"), |
| 59 |
[ |
| 60 |
"John Smith", |
| 61 |
"Rhonda", |
| 62 |
], |
| 63 |
lambda a: a.name, |
| 64 |
) |
| 65 |
|
| 66 |
def test_function_as_filter(self): |
| 67 |
Author.objects.create(name="John Smith", alias="SMITHJ") |
| 68 |
Author.objects.create(name="Rhonda") |
| 69 |
self.assertQuerySetEqual( |
| 70 |
Author.objects.filter(alias=Upper(V("smithj"))), |
| 71 |
["John Smith"], |
| 72 |
lambda x: x.name, |
| 73 |
) |
| 74 |
self.assertQuerySetEqual( |
| 75 |
Author.objects.exclude(alias=Upper(V("smithj"))), |
| 76 |
["Rhonda"], |
| 77 |
lambda x: x.name, |
| 78 |
) |