#36764: QuerySet.only() causes n+1 queries with reverse foreign key relation
-------------------------------------+-------------------------------------
Reporter: Bernhard Vallant | Owner: (none)
Type: Bug | Status: new
Component: Database layer | Version: dev
(models, ORM) |
Severity: Normal | Resolution:
Keywords: queryset, only, | Triage Stage:
defered | Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Youngkwang Yang):
{{{#!python
Product.objects.all().delete()
Category.objects.all().delete()
category = Category.objects.create(name="Test")
Product.objects.create(name="P1", price=10, category=category)
Product.objects.create(name="P2", price=20, category=category)
# Test
qs = category.product_set.only("name")
print(f"_known_related_objects: {qs._known_related_objects}")
reset_queries()
for p in qs:
p.name # only accessing 'name', but triggers extra queries
print(f"\nQueries executed: {len(connection.queries)}")
for q in connection.queries:
print(f" {q['sql']}")
}}}
output:
{{{#!shell
_known_related_objects: {<ForeignKey: category>: {10011: <Category:
Test>}}
Queries executed: 3
SELECT "product"."id", "product"."name" FROM "product" WHERE
"product"."related_id" = 10011
SELECT "product"."id", "product"."related_id" FROM "product" WHERE
"product"."id" = 100020 LIMIT 21
SELECT "product"."id", "product"."related_id" FROM "product" WHERE
"product"."id" = 100021 LIMIT 21
}}}
this problem seems related to `_known_related_objects` in
`RelatedManager._apply_rel_filters()`, which causes Django to access the
deferred `related_id` on each instance.
--
Ticket URL: <https://code.djangoproject.com/ticket/36764#comment:3>
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 view this discussion visit
https://groups.google.com/d/msgid/django-updates/0107019adf97d3eb-01563538-f662-418a-8586-caf35ddf6d19-000000%40eu-central-1.amazonses.com.