summaryrefslogtreecommitdiff
path: root/django
diff options
context:
space:
mode:
authorHannes Ljungberg <hannes.ljungberg@gmail.com>2021-11-27 16:04:39 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2021-11-29 06:27:22 +0100
commited2018037d152eef7e68f339b4562f8aadc2b7a0 (patch)
tree8fe1a910d8221fa244edbcc4ae921fb239eab8a2 /django
parent9ac92b1efc5ff90e7cce5c47fbd05887d403e4cd (diff)
Fixed #33322 -- Fixed loss of assigned related object when saving relation with bulk_update().
Diffstat (limited to 'django')
-rw-r--r--django/db/models/base.py4
-rw-r--r--django/db/models/query.py2
2 files changed, 5 insertions, 1 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 29bbde5e6b..237a04cfd7 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -931,11 +931,13 @@ class Model(metaclass=ModelBase):
using=using, raw=raw,
)
- def _prepare_related_fields_for_save(self, operation_name):
+ def _prepare_related_fields_for_save(self, operation_name, fields=None):
# Ensure that a model instance without a PK hasn't been assigned to
# a ForeignKey or OneToOneField on this model. If the field is
# nullable, allowing the save would result in silent data loss.
for field in self._meta.concrete_fields:
+ if fields and field not in fields:
+ continue
# If the related field isn't cached, then an instance hasn't been
# assigned and there's no need to worry about this check.
if field.is_relation and field.is_cached(self):
diff --git a/django/db/models/query.py b/django/db/models/query.py
index fc36945f56..fb6639793a 100644
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -549,6 +549,8 @@ class QuerySet:
raise ValueError('bulk_update() cannot be used with primary key fields.')
if not objs:
return 0
+ for obj in objs:
+ obj._prepare_related_fields_for_save(operation_name='bulk_update', fields=fields)
# PK is used twice in the resulting update query, once in the filter
# and once in the WHEN. Each field will also have one CAST.
connection = connections[self.db]