test_length.py 1.7 KB

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