2
Regression tests for proper working of ForeignKey(null=True). Tests these bugs:
4
* #7512: including a nullable foreign key reference in Meta ordering has un
9
from django.db import models
11
# The first two models represent a very simple null FK ordering case.
12
class Author(models.Model):
13
name = models.CharField(max_length=150)
15
class Article(models.Model):
16
title = models.CharField(max_length=150)
17
author = models.ForeignKey(Author, null=True)
19
def __unicode__(self):
20
return u'Article titled: %s' % (self.title, )
23
ordering = ['author__name', ]
26
# These following 4 models represent a far more complex ordering case.
27
class SystemInfo(models.Model):
28
system_name = models.CharField(max_length=32)
30
class Forum(models.Model):
31
system_info = models.ForeignKey(SystemInfo)
32
forum_name = models.CharField(max_length=32)
34
class Post(models.Model):
35
forum = models.ForeignKey(Forum, null=True)
36
title = models.CharField(max_length=32)
38
def __unicode__(self):
41
class Comment(models.Model):
42
post = models.ForeignKey(Post, null=True)
43
comment_text = models.CharField(max_length=250)
46
ordering = ['post__forum__system_info__system_name', 'comment_text']
48
def __unicode__(self):
49
return self.comment_text
52
__test__ = {'API_TESTS': """
53
# Regression test for #7512 -- ordering across nullable Foreign Keys shouldn't
55
>>> author_1 = Author.objects.create(name='Tom Jones')
56
>>> author_2 = Author.objects.create(name='Bob Smith')
57
>>> article_1 = Article.objects.create(title='No author on this article')
58
>>> article_2 = Article.objects.create(author=author_1, title='This article written by Tom Jones')
59
>>> article_3 = Article.objects.create(author=author_2, title='This article written by Bob Smith')
61
# We can't compare results directly (since different databases sort NULLs to
62
# different ends of the ordering), but we can check that all results are
64
>>> len(list(Article.objects.all())) == 3
67
>>> s = SystemInfo.objects.create(system_name='System Info')
68
>>> f = Forum.objects.create(system_info=s, forum_name='First forum')
69
>>> p = Post.objects.create(forum=f, title='First Post')
70
>>> c1 = Comment.objects.create(post=p, comment_text='My first comment')
71
>>> c2 = Comment.objects.create(comment_text='My second comment')
72
>>> s2 = SystemInfo.objects.create(system_name='More System Info')
73
>>> f2 = Forum.objects.create(system_info=s2, forum_name='Second forum')
74
>>> p2 = Post.objects.create(forum=f2, title='Second Post')
75
>>> c3 = Comment.objects.create(comment_text='Another first comment')
76
>>> c4 = Comment.objects.create(post=p2, comment_text='Another second comment')
78
# We have to test this carefully. Some databases sort NULL values before
79
# everything else, some sort them afterwards. So we extract the ordered list
80
# and check the length. Before the fix, this list was too short (some values
82
>>> len(list(Comment.objects.all())) == 4