1 from __future__
import absolute_import
3 from django
.test
import TestCase
4 from django
.core
.exceptions
import FieldError
6 from .models
import Poll
, Choice
, OuterA
, Inner
, OuterB
9 class NullQueriesTests(TestCase
):
11 def test_none_as_null(self
):
13 Regression test for the use of None as a query value.
15 None is interpreted as an SQL NULL, but only in __exact queries.
16 Set up some initial polls and choices
18 p1
= Poll(question
='Why?')
20 c1
= Choice(poll
=p1
, choice
='Because.')
22 c2
= Choice(poll
=p1
, choice
='Why Not?')
25 # Exact query with value None returns nothing ("is NULL" in sql,
26 # but every 'id' field has a value).
27 self
.assertQuerysetEqual(Choice
.objects
.filter(choice__exact
=None), [])
29 # Excluding the previous result returns everything.
30 self
.assertQuerysetEqual(
31 Choice
.objects
.exclude(choice
=None).order_by('id'),
33 '<Choice: Choice: Because. in poll Q: Why? >',
34 '<Choice: Choice: Why Not? in poll Q: Why? >'
38 # Valid query, but fails because foo isn't a keyword
39 self
.assertRaises(FieldError
, Choice
.objects
.filter, foo__exact
=None)
41 # Can't use None on anything other than __exact
42 self
.assertRaises(ValueError, Choice
.objects
.filter, id__gt
=None)
44 # Can't use None on anything other than __exact
45 self
.assertRaises(ValueError, Choice
.objects
.filter, foo__gt
=None)
47 # Related managers use __exact=None implicitly if the object hasn't been saved.
48 p2
= Poll(question
="How?")
49 self
.assertEqual(repr(p2
.choice_set
.all()), '[]')
51 def test_reverse_relations(self
):
53 Querying across reverse relations and then another relation should
54 insert outer joins correctly so as not to exclude results.
56 obj
= OuterA
.objects
.create()
57 self
.assertQuerysetEqual(
58 OuterA
.objects
.filter(inner__second
=None),
59 ['<OuterA: OuterA object>']
61 self
.assertQuerysetEqual(
62 OuterA
.objects
.filter(inner__second__data
=None),
63 ['<OuterA: OuterA object>']
66 inner_obj
= Inner
.objects
.create(first
=obj
)
67 self
.assertQuerysetEqual(
68 Inner
.objects
.filter(first__inner__second
=None),
69 ['<Inner: Inner object>']
72 # Ticket #13815: check if <reverse>_isnull=False does not produce
74 objB
= OuterB
.objects
.create(data
="reverse")
75 self
.assertQuerysetEqual(
76 OuterB
.objects
.filter(inner__isnull
=False),
79 Inner
.objects
.create(first
=obj
)
80 self
.assertQuerysetEqual(
81 OuterB
.objects
.exclude(inner__isnull
=False),
82 ['<OuterB: OuterB object>']