summaryrefslogtreecommitdiff
path: root/django
diff options
context:
space:
mode:
authorAndrei Antoukh <niwi@niwi.be>2012-08-12 22:17:54 +0300
committerAnssi Kääriäinen <akaariai@gmail.com>2012-08-12 22:39:27 +0300
commit99321e30cebbffeafc6ae19f4f92a0a665cbf19b (patch)
tree668b2766ef18a603d18253a12a8e00cfd5dde0c2 /django
parent59a655988ee95e4b4e4646cebea88b620d8fcdd2 (diff)
Fixed #18306 -- Made deferred models issue update_fields on save
Deferred models now automatically update only the fields which are loaded from the db (with .only() or .defer()). In addition, any field set manually after the load is updated on save.
Diffstat (limited to 'django')
-rw-r--r--django/db/models/base.py18
1 files changed, 18 insertions, 0 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 30e07be3a7..1e1a138714 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -475,6 +475,7 @@ class Model(six.with_metaclass(ModelBase, object)):
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally, they should not be set.
"""
+ using = using or router.db_for_write(self.__class__, instance=self)
if force_insert and (force_update or update_fields):
raise ValueError("Cannot force both insert and updating in model saving.")
@@ -502,6 +503,23 @@ class Model(six.with_metaclass(ModelBase, object)):
"model or are m2m fields: %s"
% ', '.join(non_model_fields))
+ # If saving to the same database, and this model is deferred, then
+ # automatically do a "update_fields" save on the loaded fields.
+ elif not force_insert and self._deferred and using == self._state.db:
+ field_names = set()
+ for field in self._meta.fields:
+ if not field.primary_key and not hasattr(field, 'through'):
+ field_names.add(field.attname)
+ deferred_fields = [
+ f.attname for f in self._meta.fields
+ if f.attname not in self.__dict__
+ and isinstance(self.__class__.__dict__[f.attname],
+ DeferredAttribute)]
+
+ loaded_fields = field_names.difference(deferred_fields)
+ if loaded_fields:
+ update_fields = frozenset(loaded_fields)
+
self.save_base(using=using, force_insert=force_insert,
force_update=force_update, update_fields=update_fields)
save.alters_data = True