2020-06-20 12:55:03 +08:00
|
|
|
import unittest
|
|
|
|
|
2016-06-30 00:17:40 +08:00
|
|
|
from django.core.exceptions import FieldError
|
2020-06-20 12:55:03 +08:00
|
|
|
from django.db import IntegrityError, connection, transaction
|
2020-11-16 06:43:47 +08:00
|
|
|
from django.db.models import CharField, Count, F, IntegerField, Max
|
|
|
|
from django.db.models.functions import Abs, Concat, Lower
|
2010-04-03 19:45:31 +08:00
|
|
|
from django.test import TestCase
|
2020-11-16 06:43:47 +08:00
|
|
|
from django.test.utils import register_lookup
|
2010-04-03 19:45:31 +08:00
|
|
|
|
2021-04-15 03:11:17 +08:00
|
|
|
from .models import (
|
|
|
|
A, B, Bar, D, DataPoint, Foo, RelatedPoint, UniqueNumber,
|
|
|
|
UniqueNumberChild,
|
|
|
|
)
|
2010-04-03 19:45:31 +08:00
|
|
|
|
2010-12-04 15:28:12 +08:00
|
|
|
|
2010-04-03 19:45:31 +08:00
|
|
|
class SimpleTest(TestCase):
|
2018-11-24 09:59:38 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
|
|
|
cls.a1 = A.objects.create()
|
|
|
|
cls.a2 = A.objects.create()
|
2010-04-03 19:45:31 +08:00
|
|
|
for x in range(20):
|
2018-11-24 09:59:38 +08:00
|
|
|
B.objects.create(a=cls.a1)
|
|
|
|
D.objects.create(a=cls.a1)
|
2010-04-03 19:45:31 +08:00
|
|
|
|
|
|
|
def test_nonempty_update(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Update changes the right number of rows for a nonempty queryset
|
2010-04-03 19:45:31 +08:00
|
|
|
"""
|
|
|
|
num_updated = self.a1.b_set.update(y=100)
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(num_updated, 20)
|
2010-04-03 19:45:31 +08:00
|
|
|
cnt = B.objects.filter(y=100).count()
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(cnt, 20)
|
2010-04-03 19:45:31 +08:00
|
|
|
|
|
|
|
def test_empty_update(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Update changes the right number of rows for an empty queryset
|
2010-04-03 19:45:31 +08:00
|
|
|
"""
|
|
|
|
num_updated = self.a2.b_set.update(y=100)
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(num_updated, 0)
|
2010-04-03 19:45:31 +08:00
|
|
|
cnt = B.objects.filter(y=100).count()
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(cnt, 0)
|
2010-04-03 19:45:31 +08:00
|
|
|
|
|
|
|
def test_nonempty_update_with_inheritance(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Update changes the right number of rows for an empty queryset
|
2010-04-03 19:45:31 +08:00
|
|
|
when the update affects only a base table
|
|
|
|
"""
|
|
|
|
num_updated = self.a1.d_set.update(y=100)
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(num_updated, 20)
|
2010-04-03 19:45:31 +08:00
|
|
|
cnt = D.objects.filter(y=100).count()
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(cnt, 20)
|
2010-04-03 19:45:31 +08:00
|
|
|
|
|
|
|
def test_empty_update_with_inheritance(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Update changes the right number of rows for an empty queryset
|
2010-04-03 19:45:31 +08:00
|
|
|
when the update affects only a base table
|
|
|
|
"""
|
|
|
|
num_updated = self.a2.d_set.update(y=100)
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(num_updated, 0)
|
2010-04-03 19:45:31 +08:00
|
|
|
cnt = D.objects.filter(y=100).count()
|
2010-12-04 15:28:12 +08:00
|
|
|
self.assertEqual(cnt, 0)
|
2010-09-13 13:28:10 +08:00
|
|
|
|
2013-06-19 02:15:13 +08:00
|
|
|
def test_foreign_key_update_with_id(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
Update works using <field>_id for foreign keys
|
2013-06-19 02:15:13 +08:00
|
|
|
"""
|
|
|
|
num_updated = self.a1.d_set.update(a_id=self.a2)
|
|
|
|
self.assertEqual(num_updated, 20)
|
|
|
|
self.assertEqual(self.a2.d_set.count(), 20)
|
|
|
|
|
|
|
|
|
2010-09-13 13:28:10 +08:00
|
|
|
class AdvancedTests(TestCase):
|
|
|
|
|
2018-11-24 09:59:38 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
|
|
|
cls.d0 = DataPoint.objects.create(name="d0", value="apple")
|
|
|
|
cls.d2 = DataPoint.objects.create(name="d2", value="banana")
|
|
|
|
cls.d3 = DataPoint.objects.create(name="d3", value="banana")
|
|
|
|
cls.r1 = RelatedPoint.objects.create(name="r1", data=cls.d3)
|
2010-09-13 13:28:10 +08:00
|
|
|
|
|
|
|
def test_update(self):
|
|
|
|
"""
|
|
|
|
Objects are updated by first filtering the candidates into a queryset
|
|
|
|
and then calling the update() method. It executes immediately and
|
|
|
|
returns nothing.
|
|
|
|
"""
|
|
|
|
resp = DataPoint.objects.filter(value="apple").update(name="d1")
|
|
|
|
self.assertEqual(resp, 1)
|
|
|
|
resp = DataPoint.objects.filter(value="apple")
|
|
|
|
self.assertEqual(list(resp), [self.d0])
|
|
|
|
|
|
|
|
def test_update_multiple_objects(self):
|
|
|
|
"""
|
|
|
|
We can update multiple objects at once.
|
|
|
|
"""
|
2018-03-16 17:54:34 +08:00
|
|
|
resp = DataPoint.objects.filter(value='banana').update(value='pineapple')
|
2010-09-13 13:28:10 +08:00
|
|
|
self.assertEqual(resp, 2)
|
2012-06-08 00:08:47 +08:00
|
|
|
self.assertEqual(DataPoint.objects.get(name="d2").value, 'pineapple')
|
2010-09-13 13:28:10 +08:00
|
|
|
|
|
|
|
def test_update_fk(self):
|
|
|
|
"""
|
|
|
|
Foreign key fields can also be updated, although you can only update
|
|
|
|
the object referred to, not anything inside the related object.
|
|
|
|
"""
|
|
|
|
resp = RelatedPoint.objects.filter(name="r1").update(data=self.d0)
|
|
|
|
self.assertEqual(resp, 1)
|
|
|
|
resp = RelatedPoint.objects.filter(data__name="d0")
|
|
|
|
self.assertEqual(list(resp), [self.r1])
|
|
|
|
|
|
|
|
def test_update_multiple_fields(self):
|
|
|
|
"""
|
|
|
|
Multiple fields can be updated at once
|
|
|
|
"""
|
|
|
|
resp = DataPoint.objects.filter(value="apple").update(
|
|
|
|
value="fruit", another_value="peach")
|
|
|
|
self.assertEqual(resp, 1)
|
|
|
|
d = DataPoint.objects.get(name="d0")
|
2012-06-08 00:08:47 +08:00
|
|
|
self.assertEqual(d.value, 'fruit')
|
|
|
|
self.assertEqual(d.another_value, 'peach')
|
2010-09-13 13:28:10 +08:00
|
|
|
|
|
|
|
def test_update_all(self):
|
|
|
|
"""
|
|
|
|
In the rare case you want to update every instance of a model, update()
|
|
|
|
is also a manager method.
|
|
|
|
"""
|
|
|
|
self.assertEqual(DataPoint.objects.update(value='thing'), 3)
|
|
|
|
resp = DataPoint.objects.values('value').distinct()
|
2012-06-08 00:08:47 +08:00
|
|
|
self.assertEqual(list(resp), [{'value': 'thing'}])
|
2010-09-13 13:28:10 +08:00
|
|
|
|
|
|
|
def test_update_slice_fail(self):
|
|
|
|
"""
|
|
|
|
We do not support update on already sliced query sets.
|
|
|
|
"""
|
|
|
|
method = DataPoint.objects.all()[:2].update
|
2017-05-29 03:37:21 +08:00
|
|
|
msg = 'Cannot update a query once a slice has been taken.'
|
2021-03-10 16:16:28 +08:00
|
|
|
with self.assertRaisesMessage(TypeError, msg):
|
2016-01-17 19:26:39 +08:00
|
|
|
method(another_value='another thing')
|
2014-11-16 03:36:41 +08:00
|
|
|
|
|
|
|
def test_update_respects_to_field(self):
|
|
|
|
"""
|
|
|
|
Update of an FK field which specifies a to_field works.
|
|
|
|
"""
|
|
|
|
a_foo = Foo.objects.create(target='aaa')
|
|
|
|
b_foo = Foo.objects.create(target='bbb')
|
|
|
|
bar = Bar.objects.create(foo=a_foo)
|
|
|
|
self.assertEqual(bar.foo_id, a_foo.target)
|
|
|
|
bar_qs = Bar.objects.filter(pk=bar.pk)
|
|
|
|
self.assertEqual(bar_qs[0].foo_id, a_foo.target)
|
|
|
|
bar_qs.update(foo=b_foo)
|
|
|
|
self.assertEqual(bar_qs[0].foo_id, b_foo.target)
|
2016-06-30 00:17:40 +08:00
|
|
|
|
2017-07-08 01:01:38 +08:00
|
|
|
def test_update_m2m_field(self):
|
|
|
|
msg = (
|
|
|
|
'Cannot update model field '
|
|
|
|
'<django.db.models.fields.related.ManyToManyField: m2m_foo> '
|
|
|
|
'(only non-relations and foreign keys permitted).'
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(FieldError, msg):
|
|
|
|
Bar.objects.update(m2m_foo='whatever')
|
|
|
|
|
2020-11-16 06:43:47 +08:00
|
|
|
def test_update_transformed_field(self):
|
|
|
|
A.objects.create(x=5)
|
|
|
|
A.objects.create(x=-6)
|
|
|
|
with register_lookup(IntegerField, Abs):
|
|
|
|
A.objects.update(x=F('x__abs'))
|
|
|
|
self.assertCountEqual(A.objects.values_list('x', flat=True), [5, 6])
|
|
|
|
|
2016-06-30 00:17:40 +08:00
|
|
|
def test_update_annotated_queryset(self):
|
|
|
|
"""
|
|
|
|
Update of a queryset that's been annotated.
|
|
|
|
"""
|
|
|
|
# Trivial annotated update
|
|
|
|
qs = DataPoint.objects.annotate(alias=F('value'))
|
|
|
|
self.assertEqual(qs.update(another_value='foo'), 3)
|
|
|
|
# Update where annotation is used for filtering
|
|
|
|
qs = DataPoint.objects.annotate(alias=F('value')).filter(alias='apple')
|
|
|
|
self.assertEqual(qs.update(another_value='foo'), 1)
|
|
|
|
# Update where annotation is used in update parameters
|
|
|
|
qs = DataPoint.objects.annotate(alias=F('value'))
|
|
|
|
self.assertEqual(qs.update(another_value=F('alias')), 3)
|
|
|
|
# Update where aggregation annotation is used in update parameters
|
|
|
|
qs = DataPoint.objects.annotate(max=Max('value'))
|
2019-02-15 07:58:08 +08:00
|
|
|
msg = (
|
|
|
|
'Aggregate functions are not allowed in this query '
|
|
|
|
'(another_value=Max(Col(update_datapoint, update.DataPoint.value))).'
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(FieldError, msg):
|
2016-06-30 00:17:40 +08:00
|
|
|
qs.update(another_value=F('max'))
|
2016-04-18 01:03:08 +08:00
|
|
|
|
|
|
|
def test_update_annotated_multi_table_queryset(self):
|
|
|
|
"""
|
|
|
|
Update of a queryset that's been annotated and involves multiple tables.
|
|
|
|
"""
|
|
|
|
# Trivial annotated update
|
|
|
|
qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
|
|
|
|
self.assertEqual(qs.update(value='Foo'), 3)
|
|
|
|
# Update where annotation is used for filtering
|
|
|
|
qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
|
|
|
|
self.assertEqual(qs.filter(related_count=1).update(value='Foo'), 1)
|
|
|
|
# Update where aggregation annotation is used in update parameters
|
|
|
|
qs = RelatedPoint.objects.annotate(max=Max('data__value'))
|
2019-06-28 03:13:48 +08:00
|
|
|
msg = 'Joined field references are not permitted in this query'
|
2019-02-15 07:58:08 +08:00
|
|
|
with self.assertRaisesMessage(FieldError, msg):
|
2016-04-18 01:03:08 +08:00
|
|
|
qs.update(name=F('max'))
|
2019-06-28 03:13:48 +08:00
|
|
|
|
|
|
|
def test_update_with_joined_field_annotation(self):
|
|
|
|
msg = 'Joined field references are not permitted in this query'
|
2020-11-16 06:43:47 +08:00
|
|
|
with register_lookup(CharField, Lower):
|
|
|
|
for annotation in (
|
|
|
|
F('data__name'),
|
|
|
|
F('data__name__lower'),
|
|
|
|
Lower('data__name'),
|
|
|
|
Concat('data__name', 'data__value'),
|
|
|
|
):
|
|
|
|
with self.subTest(annotation=annotation):
|
|
|
|
with self.assertRaisesMessage(FieldError, msg):
|
|
|
|
RelatedPoint.objects.annotate(
|
|
|
|
new_name=annotation,
|
|
|
|
).update(name=F('new_name'))
|
2020-06-20 12:55:03 +08:00
|
|
|
|
|
|
|
|
|
|
|
@unittest.skipUnless(
|
|
|
|
connection.vendor == 'mysql',
|
|
|
|
'UPDATE...ORDER BY syntax is supported on MySQL/MariaDB',
|
|
|
|
)
|
|
|
|
class MySQLUpdateOrderByTest(TestCase):
|
|
|
|
"""Update field with a unique constraint using an ordered queryset."""
|
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
|
|
|
UniqueNumber.objects.create(number=1)
|
|
|
|
UniqueNumber.objects.create(number=2)
|
|
|
|
|
|
|
|
def test_order_by_update_on_unique_constraint(self):
|
|
|
|
tests = [
|
|
|
|
('-number', 'id'),
|
|
|
|
(F('number').desc(), 'id'),
|
|
|
|
(F('number') * -1, 'id'),
|
|
|
|
]
|
|
|
|
for ordering in tests:
|
|
|
|
with self.subTest(ordering=ordering), transaction.atomic():
|
|
|
|
updated = UniqueNumber.objects.order_by(*ordering).update(
|
|
|
|
number=F('number') + 1,
|
|
|
|
)
|
|
|
|
self.assertEqual(updated, 2)
|
|
|
|
|
|
|
|
def test_order_by_update_on_unique_constraint_annotation(self):
|
|
|
|
# Ordering by annotations is omitted because they cannot be resolved in
|
|
|
|
# .update().
|
|
|
|
with self.assertRaises(IntegrityError):
|
|
|
|
UniqueNumber.objects.annotate(
|
|
|
|
number_inverse=F('number').desc(),
|
|
|
|
).order_by('number_inverse').update(
|
|
|
|
number=F('number') + 1,
|
|
|
|
)
|
2021-04-15 03:11:17 +08:00
|
|
|
|
|
|
|
def test_order_by_update_on_parent_unique_constraint(self):
|
|
|
|
# Ordering by inherited fields is omitted because joined fields cannot
|
|
|
|
# be used in the ORDER BY clause.
|
|
|
|
UniqueNumberChild.objects.create(number=3)
|
|
|
|
UniqueNumberChild.objects.create(number=4)
|
|
|
|
with self.assertRaises(IntegrityError):
|
|
|
|
UniqueNumberChild.objects.order_by('number').update(
|
|
|
|
number=F('number') + 1,
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_order_by_update_on_related_field(self):
|
|
|
|
# Ordering by related fields is omitted because joined fields cannot be
|
|
|
|
# used in the ORDER BY clause.
|
|
|
|
data = DataPoint.objects.create(name='d0', value='apple')
|
|
|
|
related = RelatedPoint.objects.create(name='r0', data=data)
|
|
|
|
with self.assertNumQueries(1) as ctx:
|
|
|
|
updated = RelatedPoint.objects.order_by('data__name').update(name='new')
|
|
|
|
sql = ctx.captured_queries[0]['sql']
|
|
|
|
self.assertNotIn('ORDER BY', sql)
|
|
|
|
self.assertEqual(updated, 1)
|
|
|
|
related.refresh_from_db()
|
|
|
|
self.assertEqual(related.name, 'new')
|