#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.

-- 
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/01070192c3b0e333-597a1151-5fba-45d3-b0db-0a05f750c7c5-000000%40eu-central-1.amazonses.com.

Reply via email to