tests.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import unittest
  2. from django.core.exceptions import FieldError
  3. from django.db import IntegrityError, connection, transaction
  4. from django.db.models import CharField, Count, F, IntegerField, Max
  5. from django.db.models.functions import Abs, Concat, Lower
  6. from django.test import TestCase
  7. from django.test.utils import register_lookup
  8. from .models import A, B, Bar, D, DataPoint, Foo, RelatedPoint, UniqueNumber
  9. class SimpleTest(TestCase):
  10. @classmethod
  11. def setUpTestData(cls):
  12. cls.a1 = A.objects.create()
  13. cls.a2 = A.objects.create()
  14. for x in range(20):
  15. B.objects.create(a=cls.a1)
  16. D.objects.create(a=cls.a1)
  17. def test_nonempty_update(self):
  18. """
  19. Update changes the right number of rows for a nonempty queryset
  20. """
  21. num_updated = self.a1.b_set.update(y=100)
  22. self.assertEqual(num_updated, 20)
  23. cnt = B.objects.filter(y=100).count()
  24. self.assertEqual(cnt, 20)
  25. def test_empty_update(self):
  26. """
  27. Update changes the right number of rows for an empty queryset
  28. """
  29. num_updated = self.a2.b_set.update(y=100)
  30. self.assertEqual(num_updated, 0)
  31. cnt = B.objects.filter(y=100).count()
  32. self.assertEqual(cnt, 0)
  33. def test_nonempty_update_with_inheritance(self):
  34. """
  35. Update changes the right number of rows for an empty queryset
  36. when the update affects only a base table
  37. """
  38. num_updated = self.a1.d_set.update(y=100)
  39. self.assertEqual(num_updated, 20)
  40. cnt = D.objects.filter(y=100).count()
  41. self.assertEqual(cnt, 20)
  42. def test_empty_update_with_inheritance(self):
  43. """
  44. Update changes the right number of rows for an empty queryset
  45. when the update affects only a base table
  46. """
  47. num_updated = self.a2.d_set.update(y=100)
  48. self.assertEqual(num_updated, 0)
  49. cnt = D.objects.filter(y=100).count()
  50. self.assertEqual(cnt, 0)
  51. def test_foreign_key_update_with_id(self):
  52. """
  53. Update works using <field>_id for foreign keys
  54. """
  55. num_updated = self.a1.d_set.update(a_id=self.a2)
  56. self.assertEqual(num_updated, 20)
  57. self.assertEqual(self.a2.d_set.count(), 20)
  58. class AdvancedTests(TestCase):
  59. @classmethod
  60. def setUpTestData(cls):
  61. cls.d0 = DataPoint.objects.create(name="d0", value="apple")
  62. cls.d2 = DataPoint.objects.create(name="d2", value="banana")
  63. cls.d3 = DataPoint.objects.create(name="d3", value="banana")
  64. cls.r1 = RelatedPoint.objects.create(name="r1", data=cls.d3)
  65. def test_update(self):
  66. """
  67. Objects are updated by first filtering the candidates into a queryset
  68. and then calling the update() method. It executes immediately and
  69. returns nothing.
  70. """
  71. resp = DataPoint.objects.filter(value="apple").update(name="d1")
  72. self.assertEqual(resp, 1)
  73. resp = DataPoint.objects.filter(value="apple")
  74. self.assertEqual(list(resp), [self.d0])
  75. def test_update_multiple_objects(self):
  76. """
  77. We can update multiple objects at once.
  78. """
  79. resp = DataPoint.objects.filter(value='banana').update(value='pineapple')
  80. self.assertEqual(resp, 2)
  81. self.assertEqual(DataPoint.objects.get(name="d2").value, 'pineapple')
  82. def test_update_fk(self):
  83. """
  84. Foreign key fields can also be updated, although you can only update
  85. the object referred to, not anything inside the related object.
  86. """
  87. resp = RelatedPoint.objects.filter(name="r1").update(data=self.d0)
  88. self.assertEqual(resp, 1)
  89. resp = RelatedPoint.objects.filter(data__name="d0")
  90. self.assertEqual(list(resp), [self.r1])
  91. def test_update_multiple_fields(self):
  92. """
  93. Multiple fields can be updated at once
  94. """
  95. resp = DataPoint.objects.filter(value="apple").update(
  96. value="fruit", another_value="peach")
  97. self.assertEqual(resp, 1)
  98. d = DataPoint.objects.get(name="d0")
  99. self.assertEqual(d.value, 'fruit')
  100. self.assertEqual(d.another_value, 'peach')
  101. def test_update_all(self):
  102. """
  103. In the rare case you want to update every instance of a model, update()
  104. is also a manager method.
  105. """
  106. self.assertEqual(DataPoint.objects.update(value='thing'), 3)
  107. resp = DataPoint.objects.values('value').distinct()
  108. self.assertEqual(list(resp), [{'value': 'thing'}])
  109. def test_update_slice_fail(self):
  110. """
  111. We do not support update on already sliced query sets.
  112. """
  113. method = DataPoint.objects.all()[:2].update
  114. msg = 'Cannot update a query once a slice has been taken.'
  115. with self.assertRaisesMessage(AssertionError, msg):
  116. method(another_value='another thing')
  117. def test_update_respects_to_field(self):
  118. """
  119. Update of an FK field which specifies a to_field works.
  120. """
  121. a_foo = Foo.objects.create(target='aaa')
  122. b_foo = Foo.objects.create(target='bbb')
  123. bar = Bar.objects.create(foo=a_foo)
  124. self.assertEqual(bar.foo_id, a_foo.target)
  125. bar_qs = Bar.objects.filter(pk=bar.pk)
  126. self.assertEqual(bar_qs[0].foo_id, a_foo.target)
  127. bar_qs.update(foo=b_foo)
  128. self.assertEqual(bar_qs[0].foo_id, b_foo.target)
  129. def test_update_m2m_field(self):
  130. msg = (
  131. 'Cannot update model field '
  132. '<django.db.models.fields.related.ManyToManyField: m2m_foo> '
  133. '(only non-relations and foreign keys permitted).'
  134. )
  135. with self.assertRaisesMessage(FieldError, msg):
  136. Bar.objects.update(m2m_foo='whatever')
  137. def test_update_transformed_field(self):
  138. A.objects.create(x=5)
  139. A.objects.create(x=-6)
  140. with register_lookup(IntegerField, Abs):
  141. A.objects.update(x=F('x__abs'))
  142. self.assertCountEqual(A.objects.values_list('x', flat=True), [5, 6])
  143. def test_update_annotated_queryset(self):
  144. """
  145. Update of a queryset that's been annotated.
  146. """
  147. # Trivial annotated update
  148. qs = DataPoint.objects.annotate(alias=F('value'))
  149. self.assertEqual(qs.update(another_value='foo'), 3)
  150. # Update where annotation is used for filtering
  151. qs = DataPoint.objects.annotate(alias=F('value')).filter(alias='apple')
  152. self.assertEqual(qs.update(another_value='foo'), 1)
  153. # Update where annotation is used in update parameters
  154. qs = DataPoint.objects.annotate(alias=F('value'))
  155. self.assertEqual(qs.update(another_value=F('alias')), 3)
  156. # Update where aggregation annotation is used in update parameters
  157. qs = DataPoint.objects.annotate(max=Max('value'))
  158. msg = (
  159. 'Aggregate functions are not allowed in this query '
  160. '(another_value=Max(Col(update_datapoint, update.DataPoint.value))).'
  161. )
  162. with self.assertRaisesMessage(FieldError, msg):
  163. qs.update(another_value=F('max'))
  164. def test_update_annotated_multi_table_queryset(self):
  165. """
  166. Update of a queryset that's been annotated and involves multiple tables.
  167. """
  168. # Trivial annotated update
  169. qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
  170. self.assertEqual(qs.update(value='Foo'), 3)
  171. # Update where annotation is used for filtering
  172. qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
  173. self.assertEqual(qs.filter(related_count=1).update(value='Foo'), 1)
  174. # Update where aggregation annotation is used in update parameters
  175. qs = RelatedPoint.objects.annotate(max=Max('data__value'))
  176. msg = 'Joined field references are not permitted in this query'
  177. with self.assertRaisesMessage(FieldError, msg):
  178. qs.update(name=F('max'))
  179. def test_update_with_joined_field_annotation(self):
  180. msg = 'Joined field references are not permitted in this query'
  181. with register_lookup(CharField, Lower):
  182. for annotation in (
  183. F('data__name'),
  184. F('data__name__lower'),
  185. Lower('data__name'),
  186. Concat('data__name', 'data__value'),
  187. ):
  188. with self.subTest(annotation=annotation):
  189. with self.assertRaisesMessage(FieldError, msg):
  190. RelatedPoint.objects.annotate(
  191. new_name=annotation,
  192. ).update(name=F('new_name'))
  193. @unittest.skipUnless(
  194. connection.vendor == 'mysql',
  195. 'UPDATE...ORDER BY syntax is supported on MySQL/MariaDB',
  196. )
  197. class MySQLUpdateOrderByTest(TestCase):
  198. """Update field with a unique constraint using an ordered queryset."""
  199. @classmethod
  200. def setUpTestData(cls):
  201. UniqueNumber.objects.create(number=1)
  202. UniqueNumber.objects.create(number=2)
  203. def test_order_by_update_on_unique_constraint(self):
  204. tests = [
  205. ('-number', 'id'),
  206. (F('number').desc(), 'id'),
  207. (F('number') * -1, 'id'),
  208. ]
  209. for ordering in tests:
  210. with self.subTest(ordering=ordering), transaction.atomic():
  211. updated = UniqueNumber.objects.order_by(*ordering).update(
  212. number=F('number') + 1,
  213. )
  214. self.assertEqual(updated, 2)
  215. def test_order_by_update_on_unique_constraint_annotation(self):
  216. # Ordering by annotations is omitted because they cannot be resolved in
  217. # .update().
  218. with self.assertRaises(IntegrityError):
  219. UniqueNumber.objects.annotate(
  220. number_inverse=F('number').desc(),
  221. ).order_by('number_inverse').update(
  222. number=F('number') + 1,
  223. )