Hello, I think there is potential room for improvement with how Django handles count() queries, specifically relating to annotations. Currently any annotations that are added to a queryset are included in the SQL statement that is generated in the count() query, including all joins and SQL function calls - I've personally been bitten by this with DRF and a query with a particularly complex set of annotations where the count query took longer than fetching the data itself, but was semantically equivalent to a much faster, plain Model.objects.count() call.
I think in most cases annotations can be stripped, for example in the two queries below the annotation is not filtered on so it can be safely removed from the query without affecting the result: one = Book.objects.annotate(Count('chapters')).count() two = Book.objects.count() I wanted to gather some feedback from the group as to whether this always holds true: if an annotation is not filtered (or ordered on) it can always be safely removed from a count query? I wouldn't be surprised if there is a case where this isn't safe, but I cannot think of one. I've made an initial merge request that removes annotations from querysets that have no filter or ordering that depends on annotations here: https://github.com/django/django/pull/8928. It seems like Django also has all the information to optimize out annotations that are not directly or indirectly used by filters, but I wanted to gather some feedback before I attempted this. Tom -- You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscr...@googlegroups.com. To post to this group, send email to django-developers@googlegroups.com. Visit this group at https://groups.google.com/group/django-developers. To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/CAFNZOJM27OnuBSKWY8%3DAUkPa2vv75ASmL9yuohkH4heN8QUz2A%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.