From e03e5c751c56db5f4cb99e142c92d7d8db3a5463 Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Tue, 6 May 2025 13:57:20 -0400 Subject: Fixed #33312 -- Raised explicit exception when copying deferred model instances. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously save() would crash with an attempted forced update message, and both save(force_insert=True) and bulk_create() would crash with DoesNotExist errors trying to retrieve rows with an empty primary key (id IS NULL). Implementing deferred field model instance copying might be doable in certain cases (e.g. when all the deferred fields are db generated) but that's not trivial to implement in a backward compatible way. Thanks Adam Sołtysik for the report and test and Clifford for the review. --- docs/topics/db/queries.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'docs') diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt index eb5b323abb..bd092f524b 100644 --- a/docs/topics/db/queries.txt +++ b/docs/topics/db/queries.txt @@ -1590,6 +1590,21 @@ For example, assuming ``entry`` is already duplicated as above:: detail.entry = entry detail.save() +Note that it is not possible to copy instances of models with deferred fields +using this pattern unless values are assigned to them: + +.. code-block:: pycon + + >>> blog = Blog.objects.defer("name")[0] + >>> blog.pk = None + >>> blog._state.adding = True + >>> blog.save() + Traceback (most recent call last): + ... + AttributeError: Cannot retrieve deferred field 'name' from an unsaved model. + >>> blog.name = "Another Blog" + >>> blog.save() + .. _topics-db-queries-update: Updating multiple objects at once -- cgit v1.3