tests.py 13 KB

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