1. from django.db.models import CharField
    
  2. from django.db.models.functions import LTrim, RTrim, Trim
    
  3. from django.test import TestCase
    
  4. from django.test.utils import register_lookup
    
  5. 
    
  6. from ..models import Author
    
  7. 
    
  8. 
    
  9. class TrimTests(TestCase):
    
  10.     def test_trim(self):
    
  11.         Author.objects.create(name="  John ", alias="j")
    
  12.         Author.objects.create(name="Rhonda", alias="r")
    
  13.         authors = Author.objects.annotate(
    
  14.             ltrim=LTrim("name"),
    
  15.             rtrim=RTrim("name"),
    
  16.             trim=Trim("name"),
    
  17.         )
    
  18.         self.assertQuerysetEqual(
    
  19.             authors.order_by("alias"),
    
  20.             [
    
  21.                 ("John ", "  John", "John"),
    
  22.                 ("Rhonda", "Rhonda", "Rhonda"),
    
  23.             ],
    
  24.             lambda a: (a.ltrim, a.rtrim, a.trim),
    
  25.         )
    
  26. 
    
  27.     def test_trim_transform(self):
    
  28.         Author.objects.create(name=" John  ")
    
  29.         Author.objects.create(name="Rhonda")
    
  30.         tests = (
    
  31.             (LTrim, "John  "),
    
  32.             (RTrim, " John"),
    
  33.             (Trim, "John"),
    
  34.         )
    
  35.         for transform, trimmed_name in tests:
    
  36.             with self.subTest(transform=transform):
    
  37.                 with register_lookup(CharField, transform):
    
  38.                     authors = Author.objects.filter(
    
  39.                         **{"name__%s" % transform.lookup_name: trimmed_name}
    
  40.                     )
    
  41.                     self.assertQuerysetEqual(authors, [" John  "], lambda a: a.name)