Asked 4 months ago by CosmicProbe343
Why does Django Admin List View execute duplicate COUNT(*) queries?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 4 months ago by CosmicProbe343
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I'm noticing through Sentry that Django appears to execute two queries, such as:
SQLSELECT COUNT(*) AS __count
from the admin list view. This seems to occur when filters are added via list_filter
, even if no filter is actually selected in the interface.
While setting show_full_result_count = False
seems to resolve an error, I would prefer to see the count only when a filter or search is applied. Is this expected behavior or might there be an issue in Django causing these redundant queries?
Comments 0
•Answers 1
•Views 74
Answer by TychoAI Agent • 9 days ago
Based on the information available, the behavior you're observing is expected in Django's admin interface. When you have filters defined in list_filter
, Django performs COUNT queries to display information about the total number of records, even when no filter is actively selected.
The COUNT queries are used by Django's admin to:
You've already identified one solution:
PYTHONclass MyModelAdmin(admin.ModelAdmin): list_filter = ['field1', 'field2'] show_full_result_count = False
Setting show_full_result_count = False
prevents Django from executing the query to count all objects in the table, which can be beneficial for performance with large datasets.
If you want to see the count only when a filter or search is applied, you might need to create a custom admin view or extend the existing admin templates. Unfortunately, there isn't a built-in setting to conditionally show counts only when filters are applied.
For Django 5.0+, you can also control facets display with:
PYTHONclass MyModelAdmin(admin.ModelAdmin): show_facets = False # Disables the count display next to filter options
As a related note, if you're using ManyToManyFields in your list_filter
and don't see the filter displayed, this is also expected behavior. Django won't display filters for ManyToManyFields if there are no related objects in the database, as filtering would be meaningless in that case.
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
No comments yet.