tests.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from django.db.models import Q
  2. from django.test import TestCase
  3. from .models import Issue, User, UnicodeReferenceModel
  4. class RelatedObjectTests(TestCase):
  5. def test_related_objects_have_name_attribute(self):
  6. for field_name in ('test_issue_client', 'test_issue_cc'):
  7. obj = User._meta.get_field(field_name)
  8. self.assertEqual(field_name, obj.field.related_query_name())
  9. def test_m2m_and_m2o(self):
  10. r = User.objects.create(username="russell")
  11. g = User.objects.create(username="gustav")
  12. i1 = Issue(num=1)
  13. i1.client = r
  14. i1.save()
  15. i2 = Issue(num=2)
  16. i2.client = r
  17. i2.save()
  18. i2.cc.add(r)
  19. i3 = Issue(num=3)
  20. i3.client = g
  21. i3.save()
  22. i3.cc.add(r)
  23. self.assertQuerysetEqual(
  24. Issue.objects.filter(client=r.id), [
  25. 1,
  26. 2,
  27. ],
  28. lambda i: i.num
  29. )
  30. self.assertQuerysetEqual(
  31. Issue.objects.filter(client=g.id), [
  32. 3,
  33. ],
  34. lambda i: i.num
  35. )
  36. self.assertQuerysetEqual(
  37. Issue.objects.filter(cc__id__exact=g.id), []
  38. )
  39. self.assertQuerysetEqual(
  40. Issue.objects.filter(cc__id__exact=r.id), [
  41. 2,
  42. 3,
  43. ],
  44. lambda i: i.num
  45. )
  46. # These queries combine results from the m2m and the m2o relationships.
  47. # They're three ways of saying the same thing.
  48. self.assertQuerysetEqual(
  49. Issue.objects.filter(Q(cc__id__exact=r.id) | Q(client=r.id)), [
  50. 1,
  51. 2,
  52. 3,
  53. ],
  54. lambda i: i.num
  55. )
  56. self.assertQuerysetEqual(
  57. Issue.objects.filter(cc__id__exact=r.id) | Issue.objects.filter(client=r.id), [
  58. 1,
  59. 2,
  60. 3,
  61. ],
  62. lambda i: i.num
  63. )
  64. self.assertQuerysetEqual(
  65. Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id)), [
  66. 1,
  67. 2,
  68. 3,
  69. ],
  70. lambda i: i.num
  71. )
  72. class RelatedObjectUnicodeTests(TestCase):
  73. def test_m2m_with_unicode_reference(self):
  74. """
  75. Regression test for #6045: references to other models can be unicode
  76. strings, providing they are directly convertible to ASCII.
  77. """
  78. m1 = UnicodeReferenceModel.objects.create()
  79. m2 = UnicodeReferenceModel.objects.create()
  80. m2.others.add(m1) # used to cause an error (see ticket #6045)
  81. m2.save()
  82. list(m2.others.all()) # Force retrieval.