[Django] #34633: RelatedManager._remove_prefetched_objects() not called in RelatedManager.create()

8 views
Skip to first unread message

Django

unread,
Jun 5, 2023, 8:06:31 AM6/5/23
to django-...@googlegroups.com
#34633: RelatedManager._remove_prefetched_objects() not called in
RelatedManager.create()
-------------------------------------+-------------------------------------
Reporter: Rob | Owner: nobody
Percival |
Type: Bug | Status: new
Component: Database | Version: 4.2
layer (models, ORM) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
[https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-
related The documentation] says:
> if you call the database-altering methods add(), remove(), clear() or
set(), on related managers, any prefetched cache for the relation will be
cleared.

This is accurate. However, there are other database-altering methods, such
as create(), for which the cache ought to be cleared but isn't. This
results in this confusing state of affairs:

{{{
x = MyModel.objects.prefetch_related("related_objects").get()
assert len(x.related_objects.all()) == 0
x.related_objects.create()
assert len(x.related_objects.all()) == 1 # Assertion fails because the
prefetch cache isn't cleared by create()
}}}

Using add() rather than create() would cause the above code to work as
expected. If there's a good reason for create() not clearing the cache,
could that be documented please? Otherwise, could it clear the cache? From
a search of Stack Overflow, this is definitely a source of confusion for
some.

--
Ticket URL: <https://code.djangoproject.com/ticket/34633>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Django

unread,
Jun 5, 2023, 8:48:09 AM6/5/23
to django-...@googlegroups.com
#34633: RelatedManager._remove_prefetched_objects() not called in
RelatedManager.create()
-------------------------------------+-------------------------------------
Reporter: Rob Percival | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: 4.2
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0

Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------

Comment (by David Sanders):

The original ticket #26706, [https://groups.google.com/d/topic/django-
developers/ejOpJ_r7tv8/discussion ML thread] &
[https://github.com/django/django/pull/6725 PR] didn't seem to make any
mention of `create()`

I'd agree this seems inconsistent but keen to see what felix & charettes
(charettes reviewed the PR) think 🤔

--
Ticket URL: <https://code.djangoproject.com/ticket/34633#comment:1>

Reply all
Reply to author
Forward
0 new messages