1. from django.db.models import IntegerField, Value
    
  2. from django.db.models.functions import Lower, Right
    
  3. from django.test import TestCase
    
  4. 
    
  5. from ..models import Author
    
  6. 
    
  7. 
    
  8. class RightTests(TestCase):
    
  9.     @classmethod
    
  10.     def setUpTestData(cls):
    
  11.         Author.objects.create(name="John Smith", alias="smithj")
    
  12.         Author.objects.create(name="Rhonda")
    
  13. 
    
  14.     def test_basic(self):
    
  15.         authors = Author.objects.annotate(name_part=Right("name", 5))
    
  16.         self.assertQuerysetEqual(
    
  17.             authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part
    
  18.         )
    
  19.         # If alias is null, set it to the first 2 lower characters of the name.
    
  20.         Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2)))
    
  21.         self.assertQuerysetEqual(
    
  22.             authors.order_by("name"), ["smithj", "da"], lambda a: a.alias
    
  23.         )
    
  24. 
    
  25.     def test_invalid_length(self):
    
  26.         with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
    
  27.             Author.objects.annotate(raises=Right("name", 0))
    
  28. 
    
  29.     def test_expressions(self):
    
  30.         authors = Author.objects.annotate(
    
  31.             name_part=Right("name", Value(3, output_field=IntegerField()))
    
  32.         )
    
  33.         self.assertQuerysetEqual(
    
  34.             authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part
    
  35.         )