#25344: prefetch_related() and add() on related field
----------------------------------------------+----------------------------
Reporter: TankOs | Owner: nobody
Type: Bug | Status: new
Component: Database layer (models, ORM) | Version: 1.8
Severity: Normal | Keywords:
| prefetch_related
Triage Stage: Unreviewed | Has patch: 0
Easy pickings: 0 | UI/UX: 0
----------------------------------------------+----------------------------
When calling `add()` on a related field (ForeignKey) that has been
prefetched, albeit the added object is processed at database level, it's
not added to the prefetched collection. Following calls to `field.all()`
therefore do not contain the added object.
Example:
{{{#!python
from example.models import *
Article.objects.all().delete()
Author.objects.all().delete()
Author().save()
author = Author.objects.all().prefetch_related("articles").first()
author.articles.add(Article())
print(list(author.articles.all()))
print(list(Article.objects.all()))
}}}
Prints:
{{{
[]
[<Article: Article object>]
}}}
I could not find an info in the documentation about that behavior, and it
can be very hard to spot in bigger code bases. This should not fail
silently in my opinion, and disallowing adding to prefetched related
fields might even be an option.
Here's the link to a complete minimal project setup; the code from above
can just be pasted in a manage.py shell session:
https://github.com/TankOs/django_prefetch_add
--
Ticket URL: <https://code.djangoproject.com/ticket/25344>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/049.ada86844dbe79c57c9c33ee31c17251c%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.