[Django] #35865: Query.get_count() keeps unnecessary SQL joins

5 views
Skip to first unread message

Django

unread,
Oct 25, 2024, 8:40:07 AM10/25/24
to django-...@googlegroups.com
#35865: Query.get_count() keeps unnecessary SQL joins
-------------------------------------+-------------------------------------
Reporter: Ruslan | Type:
| Cleanup/optimization
Status: new | Component: Database
| layer (models, ORM)
Version: | Severity: Normal
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 1 | UI/UX: 0
-------------------------------------+-------------------------------------
**Problem:**
`Query.count()` results sub optimal SQL query. Though, the impact might be
minimal and highly depend on SQL engine implementation. But cleaner and
less controversial SQL is always better

**Observed behavior:**
When using `.count()` method (through QuerySet or Query — doesn't matter)
it still keeps all joins, even if they are not required for the query.

**Expected behavior:**
Calling `.count()` (`Query.get_count()`) should setup only necessary joins
and ignore any other joins that were added due to custom `QuerySet.values`
or any other method that modifies SELECT.

**Some context:**
Version: 4.x, 5.x, dev
The code (django/django/db/models/sql/query.py:635):
{{{
def get_count(self, using):
"""
Perform a COUNT() query using the current filter constraints.
"""
obj = self.clone()
return obj.get_aggregation(using, {"__count": Count("*")})["__count"]
}}}

I tried to call `obj.clear_select_clause()` but it didn't affect any
joins, because they are apparently somewhere in `Query.alias_map` and I am
not yet that familiar with how it actually works. But I will appreciate
any hints, even if it is a non-issue for a Django project itself.
--
Ticket URL: <https://code.djangoproject.com/ticket/35865>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
Reply all
Reply to author
Forward
0 new messages