1
from django.db import models
3
class Poll(models.Model):
4
question = models.CharField(max_length=200)
7
return u"Q: %s " % self.question
9
class Choice(models.Model):
10
poll = models.ForeignKey(Poll)
11
choice = models.CharField(max_length=200)
13
def __unicode__(self):
14
return u"Choice: %s in poll %s" % (self.choice, self.poll)
16
# A set of models with an inner one pointing to two outer ones.
17
class OuterA(models.Model):
20
class OuterB(models.Model):
21
data = models.CharField(max_length=10)
23
class Inner(models.Model):
24
first = models.ForeignKey(OuterA)
25
second = models.ForeignKey(OuterB, null=True)
27
__test__ = {'API_TESTS':"""
28
# Regression test for the use of None as a query value. None is interpreted as
29
# an SQL NULL, but only in __exact queries.
30
# Set up some initial polls and choices
31
>>> p1 = Poll(question='Why?')
33
>>> c1 = Choice(poll=p1, choice='Because.')
35
>>> c2 = Choice(poll=p1, choice='Why Not?')
38
# Exact query with value None returns nothing ("is NULL" in sql, but every 'id'
40
>>> Choice.objects.filter(choice__exact=None)
43
Excluding the previous result returns everything.
44
>>> Choice.objects.exclude(choice=None).order_by('id')
45
[<Choice: Choice: Because. in poll Q: Why? >, <Choice: Choice: Why Not? in poll Q: Why? >]
47
# Valid query, but fails because foo isn't a keyword
48
>>> Choice.objects.filter(foo__exact=None)
49
Traceback (most recent call last):
51
FieldError: Cannot resolve keyword 'foo' into field. Choices are: choice, id, poll
53
# Can't use None on anything other than __exact
54
>>> Choice.objects.filter(id__gt=None)
55
Traceback (most recent call last):
57
ValueError: Cannot use None as a query value
59
# Can't use None on anything other than __exact
60
>>> Choice.objects.filter(foo__gt=None)
61
Traceback (most recent call last):
63
ValueError: Cannot use None as a query value
65
# Related managers use __exact=None implicitly if the object hasn't been saved.
66
>>> p2 = Poll(question="How?")
67
>>> p2.choice_set.all()
70
# Querying across reverse relations and then another relation should insert
71
# outer joins correctly so as not to exclude results.
72
>>> obj = OuterA.objects.create()
73
>>> OuterA.objects.filter(inner__second=None)
74
[<OuterA: OuterA object>]
75
>>> OuterA.objects.filter(inner__second__data=None)
76
[<OuterA: OuterA object>]
77
>>> _ = Inner.objects.create(first=obj)
78
>>> Inner.objects.filter(first__inner__second=None)
79
[<Inner: Inner object>]