2018-03-15 19:57:23 +00:00
|
|
|
from django.db.models import CharField
|
|
|
|
from django.db.models.functions import LTrim, RTrim, Trim
|
|
|
|
from django.test import TestCase
|
2018-08-21 16:17:46 +00:00
|
|
|
from django.test.utils import register_lookup
|
2018-03-15 19:57:23 +00:00
|
|
|
|
2018-08-15 23:45:11 +00:00
|
|
|
from ..models import Author
|
2018-03-15 19:57:23 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TrimTests(TestCase):
|
|
|
|
def test_trim(self):
|
2022-02-03 19:24:19 +00:00
|
|
|
Author.objects.create(name=" John ", alias="j")
|
|
|
|
Author.objects.create(name="Rhonda", alias="r")
|
2018-03-15 19:57:23 +00:00
|
|
|
authors = Author.objects.annotate(
|
2022-02-03 19:24:19 +00:00
|
|
|
ltrim=LTrim("name"),
|
|
|
|
rtrim=RTrim("name"),
|
|
|
|
trim=Trim("name"),
|
2018-03-15 19:57:23 +00:00
|
|
|
)
|
2022-09-24 10:29:58 +00:00
|
|
|
self.assertQuerySetEqual(
|
2022-02-03 19:24:19 +00:00
|
|
|
authors.order_by("alias"),
|
|
|
|
[
|
|
|
|
("John ", " John", "John"),
|
|
|
|
("Rhonda", "Rhonda", "Rhonda"),
|
2018-03-15 19:57:23 +00:00
|
|
|
],
|
2022-02-03 19:24:19 +00:00
|
|
|
lambda a: (a.ltrim, a.rtrim, a.trim),
|
2018-03-15 19:57:23 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
def test_trim_transform(self):
|
2022-02-03 19:24:19 +00:00
|
|
|
Author.objects.create(name=" John ")
|
|
|
|
Author.objects.create(name="Rhonda")
|
2018-03-15 19:57:23 +00:00
|
|
|
tests = (
|
2022-02-03 19:24:19 +00:00
|
|
|
(LTrim, "John "),
|
|
|
|
(RTrim, " John"),
|
|
|
|
(Trim, "John"),
|
2018-03-15 19:57:23 +00:00
|
|
|
)
|
|
|
|
for transform, trimmed_name in tests:
|
|
|
|
with self.subTest(transform=transform):
|
2018-08-21 16:17:46 +00:00
|
|
|
with register_lookup(CharField, transform):
|
2022-02-03 19:24:19 +00:00
|
|
|
authors = Author.objects.filter(
|
|
|
|
**{"name__%s" % transform.lookup_name: trimmed_name}
|
|
|
|
)
|
2022-09-24 10:29:58 +00:00
|
|
|
self.assertQuerySetEqual(authors, [" John "], lambda a: a.name)
|