summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorsarahboyce <sarahvboyce95@gmail.com>2022-10-16 17:45:34 +0200
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-11-14 13:43:07 +0100
commit0678d657222dd667bcc7e4fc307ea2ab70d219d7 (patch)
tree2debf80e8ee76cd4c7615210ec21035bda3a702d /docs
parent67da22f08e05018ea968fcacbac9ac37ea925d85 (diff)
Refs #34099 -- Doc'd that custom Model.save() should update update_fields kwarg.
Diffstat (limited to 'docs')
-rw-r--r--docs/topics/db/models.txt27
1 files changed, 27 insertions, 0 deletions
diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt
index 9635e49014..2f8a5551ff 100644
--- a/docs/topics/db/models.txt
+++ b/docs/topics/db/models.txt
@@ -844,6 +844,33 @@ built-in model methods, adding new arguments. If you use ``*args,
**kwargs`` in your method definitions, you are guaranteed that your
code will automatically support those arguments when they are added.
+If you wish to update a field value in the :meth:`~Model.save` method, you may
+also want to have this field added to the ``update_fields`` keyword argument.
+This will ensure the field is saved when ``update_fields`` is specified. For
+example::
+
+ from django.db import models
+ from django.utils.text import slugify
+
+ class Blog(models.Model):
+ name = models.CharField(max_length=100)
+ slug = models.TextField()
+
+ def save(
+ self, force_insert=False, force_update=False, using=None, update_fields=None
+ ):
+ self.slug = slugify(self.name)
+ if update_fields is not None and "name" in update_fields:
+ update_fields = {"slug"}.union(update_fields)
+ super().save(
+ force_insert=force_insert,
+ force_update=force_update,
+ using=using,
+ update_fields=update_fields,
+ )
+
+See :ref:`ref-models-update-fields` for more details.
+
.. admonition:: Overridden model methods are not called on bulk operations
Note that the :meth:`~Model.delete()` method for an object is not