From f92641a636a8cb75fc9851396cef4345510a4b52 Mon Sep 17 00:00:00 2001 From: Aivars Kalvans Date: Sun, 10 Dec 2023 21:43:34 +0200 Subject: Fixed #28344 -- Allowed customizing queryset in Model.refresh_from_db()/arefresh_from_db(). The from_queryset parameter can be used to: - use a custom Manager - lock the row until the end of transaction - select additional related objects --- docs/ref/models/instances.txt | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) (limited to 'docs/ref/models') diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt index 45af7f244f..6d1a7e5db4 100644 --- a/docs/ref/models/instances.txt +++ b/docs/ref/models/instances.txt @@ -142,8 +142,8 @@ value from the database: >>> del obj.field >>> obj.field # Loads the field from the database -.. method:: Model.refresh_from_db(using=None, fields=None) -.. method:: Model.arefresh_from_db(using=None, fields=None) +.. method:: Model.refresh_from_db(using=None, fields=None, from_queryset=None) +.. method:: Model.arefresh_from_db(using=None, fields=None, from_queryset=None) *Asynchronous version*: ``arefresh_from_db()`` @@ -197,6 +197,27 @@ all of the instance's fields when a deferred field is reloaded:: fields = fields.union(deferred_fields) super().refresh_from_db(using, fields, **kwargs) +The ``from_queryset`` argument allows using a different queryset than the one +created from :attr:`~django.db.models.Model._base_manager`. It gives you more +control over how the model is reloaded. For example, when your model uses soft +deletion you can make ``refresh_from_db()`` to take this into account:: + + obj.refresh_from_db(from_queryset=MyModel.active_objects.all()) + +You can cache related objects that otherwise would be cleared from the reloaded +instance:: + + obj.refresh_from_db(from_queryset=MyModel.objects.select_related("related_field")) + +You can lock the row until the end of transaction before reloading a model's +values:: + + obj.refresh_from_db(from_queryset=MyModel.objects.select_for_update()) + +.. versionchanged:: 5.1 + + The ``from_queryset`` argument was added. + .. method:: Model.get_deferred_fields() A helper method that returns a set containing the attribute names of all those -- cgit v1.3