From ed2018037d152eef7e68f339b4562f8aadc2b7a0 Mon Sep 17 00:00:00 2001 From: Hannes Ljungberg Date: Sat, 27 Nov 2021 16:04:39 +0100 Subject: Fixed #33322 -- Fixed loss of assigned related object when saving relation with bulk_update(). --- django/db/models/base.py | 4 +++- django/db/models/query.py | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) (limited to 'django/db') 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] -- cgit v1.3