Commit 99321e30 authored by Andrei Antoukh's avatar Andrei Antoukh Committed by Anssi Kääriäinen
Browse files

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.
parent 59a65598
Loading
Loading
Loading
Loading
+18 −0
Original line number Diff line number Diff line
@@ -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
+6 −0
Original line number Diff line number Diff line
@@ -386,6 +386,12 @@ perform an update on all fields.

Specifying ``update_fields`` will force an update.

When saving a model fetched through deferred model loading
(:meth:`~Model.only()` or :meth:`~Model.defer()`) only the fields loaded from
the DB will get updated. In effect there is an automatic ``update_fields`` in
this case. If you assign or change any deferred field value, these fields will
be added to the updated fields.

Deleting objects
================

+16 −0
Original line number Diff line number Diff line
@@ -1110,6 +1110,14 @@ one, doing so will result in an error.
    reader, is slightly faster and consumes a little less memory in the Python
    process.

.. versionchanged:: 1.5

.. note::

    When calling :meth:`~Model.save()` for instances with deferred fields,
    only the loaded fields will be saved. See :meth:`~Model.save()` for more
    details.


only
~~~~
@@ -1154,6 +1162,14 @@ All of the cautions in the note for the :meth:`defer` documentation apply to
options. Also note that using :meth:`only` and omitting a field requested
using :meth:`select_related` is an error as well.

.. versionchanged:: 1.5

.. note::

    When calling :meth:`~Model.save()` for instances with deferred fields,
    only the loaded fields will be saved. See :meth:`~Model.save()` for more
    details.

using
~~~~~

+4 −0
Original line number Diff line number Diff line
@@ -42,6 +42,10 @@ keyword argument ``update_fields``. By using this argument it is possible to
save only a select list of model's fields. This can be useful for performance
reasons or when trying to avoid overwriting concurrent changes.

Deferred instances (those loaded by .only() or .defer()) will automatically
save just the loaded fields. If any field is set manually after load, that
field will also get updated on save.

See the :meth:`Model.save() <django.db.models.Model.save()>` documentation for
more details.

+1 −0
Original line number Diff line number Diff line
@@ -15,6 +15,7 @@ class Account(models.Model):
class Person(models.Model):
    name = models.CharField(max_length=20)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    pid = models.IntegerField(null=True, default=None)

    def __str__(self):
        return self.name
Loading