2018-09-19 04:14:44 +08:00
|
|
|
from datetime import date
|
|
|
|
|
2022-02-13 04:40:12 +08:00
|
|
|
from django.test import modify_settings
|
|
|
|
|
2018-09-19 04:14:44 +08:00
|
|
|
from . import PostgreSQLTestCase
|
|
|
|
from .models import (
|
2019-06-09 08:56:37 +08:00
|
|
|
HStoreModel,
|
|
|
|
IntegerArrayModel,
|
|
|
|
NestedIntegerArrayModel,
|
2018-09-19 04:14:44 +08:00
|
|
|
NullableIntegerArrayModel,
|
|
|
|
OtherTypesArrayModel,
|
|
|
|
RangesModel,
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
2020-07-24 14:25:47 +08:00
|
|
|
from psycopg2.extras import DateRange, NumericRange
|
2018-09-19 04:14:44 +08:00
|
|
|
except ImportError:
|
|
|
|
pass # psycopg2 isn't installed.
|
|
|
|
|
|
|
|
|
2022-02-13 04:40:12 +08:00
|
|
|
@modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"})
|
2018-09-19 04:14:44 +08:00
|
|
|
class BulkSaveTests(PostgreSQLTestCase):
|
|
|
|
def test_bulk_update(self):
|
|
|
|
test_data = [
|
|
|
|
(IntegerArrayModel, "field", [], [1, 2, 3]),
|
|
|
|
(NullableIntegerArrayModel, "field", [1, 2, 3], None),
|
|
|
|
(NestedIntegerArrayModel, "field", [], [[1, 2, 3]]),
|
|
|
|
(HStoreModel, "field", {}, {1: 2}),
|
|
|
|
(RangesModel, "ints", None, NumericRange(lower=1, upper=10)),
|
|
|
|
(
|
|
|
|
RangesModel,
|
|
|
|
"dates",
|
|
|
|
None,
|
|
|
|
DateRange(lower=date.today(), upper=date.today()),
|
2022-02-04 03:24:19 +08:00
|
|
|
),
|
2018-09-19 04:14:44 +08:00
|
|
|
(OtherTypesArrayModel, "ips", [], ["1.2.3.4"]),
|
|
|
|
(OtherTypesArrayModel, "json", [], [{"a": "b"}]),
|
|
|
|
]
|
|
|
|
for Model, field, initial, new in test_data:
|
|
|
|
with self.subTest(model=Model, field=field):
|
|
|
|
instances = Model.objects.bulk_create(
|
|
|
|
Model(**{field: initial}) for _ in range(20)
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2018-09-19 04:14:44 +08:00
|
|
|
for instance in instances:
|
|
|
|
setattr(instance, field, new)
|
|
|
|
Model.objects.bulk_update(instances, [field])
|
|
|
|
self.assertSequenceEqual(
|
|
|
|
Model.objects.filter(**{field: new}), instances
|
|
|
|
)
|