2
0

tests.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from __future__ import unicode_literals
  2. from django.core.exceptions import FieldError
  3. from django.test import TestCase
  4. from .models import Choice, Inner, OuterA, OuterB, Poll
  5. class NullQueriesTests(TestCase):
  6. def test_none_as_null(self):
  7. """
  8. Regression test for the use of None as a query value.
  9. None is interpreted as an SQL NULL, but only in __exact and __iexact
  10. queries.
  11. Set up some initial polls and choices
  12. """
  13. p1 = Poll(question='Why?')
  14. p1.save()
  15. c1 = Choice(poll=p1, choice='Because.')
  16. c1.save()
  17. c2 = Choice(poll=p1, choice='Why Not?')
  18. c2.save()
  19. # Exact query with value None returns nothing ("is NULL" in sql,
  20. # but every 'id' field has a value).
  21. self.assertQuerysetEqual(Choice.objects.filter(choice__exact=None), [])
  22. # The same behavior for iexact query.
  23. self.assertQuerysetEqual(Choice.objects.filter(choice__iexact=None), [])
  24. # Excluding the previous result returns everything.
  25. self.assertQuerysetEqual(
  26. Choice.objects.exclude(choice=None).order_by('id'),
  27. [
  28. '<Choice: Choice: Because. in poll Q: Why? >',
  29. '<Choice: Choice: Why Not? in poll Q: Why? >'
  30. ]
  31. )
  32. # Valid query, but fails because foo isn't a keyword
  33. with self.assertRaises(FieldError):
  34. Choice.objects.filter(foo__exact=None)
  35. # Can't use None on anything other than __exact and __iexact
  36. with self.assertRaises(ValueError):
  37. Choice.objects.filter(id__gt=None)
  38. # Related managers use __exact=None implicitly if the object hasn't been saved.
  39. p2 = Poll(question="How?")
  40. self.assertEqual(repr(p2.choice_set.all()), '<QuerySet []>')
  41. def test_reverse_relations(self):
  42. """
  43. Querying across reverse relations and then another relation should
  44. insert outer joins correctly so as not to exclude results.
  45. """
  46. obj = OuterA.objects.create()
  47. self.assertQuerysetEqual(
  48. OuterA.objects.filter(inner__third=None),
  49. ['<OuterA: OuterA object>']
  50. )
  51. self.assertQuerysetEqual(
  52. OuterA.objects.filter(inner__third__data=None),
  53. ['<OuterA: OuterA object>']
  54. )
  55. Inner.objects.create(first=obj)
  56. self.assertQuerysetEqual(
  57. Inner.objects.filter(first__inner__third=None),
  58. ['<Inner: Inner object>']
  59. )
  60. # Ticket #13815: check if <reverse>_isnull=False does not produce
  61. # faulty empty lists
  62. OuterB.objects.create(data="reverse")
  63. self.assertQuerysetEqual(
  64. OuterB.objects.filter(inner__isnull=False),
  65. []
  66. )
  67. Inner.objects.create(first=obj)
  68. self.assertQuerysetEqual(
  69. OuterB.objects.exclude(inner__isnull=False),
  70. ['<OuterB: OuterB object>']
  71. )