2
0

tests.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from django.db.models import Q
  2. from django.test import TestCase
  3. from .models import Comment, Forum, Item, Post, PropertyValue, SystemDetails, SystemInfo
  4. class NullFkTests(TestCase):
  5. def test_null_fk(self):
  6. d = SystemDetails.objects.create(details="First details")
  7. s = SystemInfo.objects.create(system_name="First forum", system_details=d)
  8. f = Forum.objects.create(system_info=s, forum_name="First forum")
  9. p = Post.objects.create(forum=f, title="First Post")
  10. c1 = Comment.objects.create(post=p, comment_text="My first comment")
  11. c2 = Comment.objects.create(comment_text="My second comment")
  12. # Starting from comment, make sure that a .select_related(...) with a specified
  13. # set of fields will properly LEFT JOIN multiple levels of NULLs (and the things
  14. # that come after the NULLs, or else data that should exist won't). Regression
  15. # test for #7369.
  16. c = Comment.objects.select_related().get(id=c1.id)
  17. self.assertEqual(c.post, p)
  18. self.assertIsNone(Comment.objects.select_related().get(id=c2.id).post)
  19. self.assertQuerySetEqual(
  20. Comment.objects.select_related("post__forum__system_info").all(),
  21. [
  22. (c1.id, "My first comment", "<Post: First Post>"),
  23. (c2.id, "My second comment", "None"),
  24. ],
  25. transform=lambda c: (c.id, c.comment_text, repr(c.post)),
  26. )
  27. # Regression test for #7530, #7716.
  28. self.assertIsNone(
  29. Comment.objects.select_related("post").filter(post__isnull=True)[0].post
  30. )
  31. self.assertQuerySetEqual(
  32. Comment.objects.select_related("post__forum__system_info__system_details"),
  33. [
  34. (c1.id, "My first comment", "<Post: First Post>"),
  35. (c2.id, "My second comment", "None"),
  36. ],
  37. transform=lambda c: (c.id, c.comment_text, repr(c.post)),
  38. )
  39. def test_combine_isnull(self):
  40. item = Item.objects.create(title="Some Item")
  41. pv = PropertyValue.objects.create(label="Some Value")
  42. item.props.create(key="a", value=pv)
  43. item.props.create(key="b") # value=NULL
  44. q1 = Q(props__key="a", props__value=pv)
  45. q2 = Q(props__key="b", props__value__isnull=True)
  46. # Each of these individually should return the item.
  47. self.assertEqual(Item.objects.get(q1), item)
  48. self.assertEqual(Item.objects.get(q2), item)
  49. # Logically, qs1 and qs2, and qs3 and qs4 should be the same.
  50. qs1 = Item.objects.filter(q1) & Item.objects.filter(q2)
  51. qs2 = Item.objects.filter(q2) & Item.objects.filter(q1)
  52. qs3 = Item.objects.filter(q1) | Item.objects.filter(q2)
  53. qs4 = Item.objects.filter(q2) | Item.objects.filter(q1)
  54. # Regression test for #15823.
  55. self.assertEqual(list(qs1), list(qs2))
  56. self.assertEqual(list(qs3), list(qs4))