1. from django.test import TestCase
    
  2. 
    
  3. from .models import Article, Author, Comment, Forum, Post, SystemInfo
    
  4. 
    
  5. 
    
  6. class NullFkOrderingTests(TestCase):
    
  7.     def test_ordering_across_null_fk(self):
    
  8.         """
    
  9.         Regression test for #7512
    
  10. 
    
  11.         ordering across nullable Foreign Keys shouldn't exclude results
    
  12.         """
    
  13.         author_1 = Author.objects.create(name="Tom Jones")
    
  14.         author_2 = Author.objects.create(name="Bob Smith")
    
  15.         Article.objects.create(title="No author on this article")
    
  16.         Article.objects.create(
    
  17.             author=author_1, title="This article written by Tom Jones"
    
  18.         )
    
  19.         Article.objects.create(
    
  20.             author=author_2, title="This article written by Bob Smith"
    
  21.         )
    
  22. 
    
  23.         # We can't compare results directly (since different databases sort NULLs to
    
  24.         # different ends of the ordering), but we can check that all results are
    
  25.         # returned.
    
  26.         self.assertEqual(len(list(Article.objects.all())), 3)
    
  27. 
    
  28.         s = SystemInfo.objects.create(system_name="System Info")
    
  29.         f = Forum.objects.create(system_info=s, forum_name="First forum")
    
  30.         p = Post.objects.create(forum=f, title="First Post")
    
  31.         Comment.objects.create(post=p, comment_text="My first comment")
    
  32.         Comment.objects.create(comment_text="My second comment")
    
  33.         s2 = SystemInfo.objects.create(system_name="More System Info")
    
  34.         f2 = Forum.objects.create(system_info=s2, forum_name="Second forum")
    
  35.         p2 = Post.objects.create(forum=f2, title="Second Post")
    
  36.         Comment.objects.create(comment_text="Another first comment")
    
  37.         Comment.objects.create(post=p2, comment_text="Another second comment")
    
  38. 
    
  39.         # We have to test this carefully. Some databases sort NULL values before
    
  40.         # everything else, some sort them afterward. So we extract the ordered list
    
  41.         # and check the length. Before the fix, this list was too short (some values
    
  42.         # were omitted).
    
  43.         self.assertEqual(len(list(Comment.objects.all())), 4)