tests.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from __future__ import unicode_literals
  2. from django.test import TestCase
  3. from django.core.exceptions import FieldError
  4. from .models import Poll, Choice, OuterA, Inner, OuterB
  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. self.assertRaises(FieldError, Choice.objects.filter, foo__exact=None)
  34. # Can't use None on anything other than __exact and __iexact
  35. self.assertRaises(ValueError, Choice.objects.filter, id__gt=None)
  36. # Related managers use __exact=None implicitly if the object hasn't been saved.
  37. p2 = Poll(question="How?")
  38. self.assertEqual(repr(p2.choice_set.all()), '[]')
  39. def test_reverse_relations(self):
  40. """
  41. Querying across reverse relations and then another relation should
  42. insert outer joins correctly so as not to exclude results.
  43. """
  44. obj = OuterA.objects.create()
  45. self.assertQuerysetEqual(
  46. OuterA.objects.filter(inner__third=None),
  47. ['<OuterA: OuterA object>']
  48. )
  49. self.assertQuerysetEqual(
  50. OuterA.objects.filter(inner__third__data=None),
  51. ['<OuterA: OuterA object>']
  52. )
  53. Inner.objects.create(first=obj)
  54. self.assertQuerysetEqual(
  55. Inner.objects.filter(first__inner__third=None),
  56. ['<Inner: Inner object>']
  57. )
  58. # Ticket #13815: check if <reverse>_isnull=False does not produce
  59. # faulty empty lists
  60. OuterB.objects.create(data="reverse")
  61. self.assertQuerysetEqual(
  62. OuterB.objects.filter(inner__isnull=False),
  63. []
  64. )
  65. Inner.objects.create(first=obj)
  66. self.assertQuerysetEqual(
  67. OuterB.objects.exclude(inner__isnull=False),
  68. ['<OuterB: OuterB object>']
  69. )