Skip to content

Optimize recent votes admin query#477

Merged
benadida merged 1 commit intomasterfrom
claude/optimize-votes-query-PHzxO
Jan 20, 2026
Merged

Optimize recent votes admin query#477
benadida merged 1 commit intomasterfrom
claude/optimize-votes-query-PHzxO

Conversation

@benadida
Copy link
Owner

Uses Django's conditional aggregation (filter=Q(...)) to correctly count and find the max cast_at only for votes within the cutoff period, and create a more efficient query.

The previous query had a bug where num_recent_cast_votes counted ALL
cast votes for elections that had at least one recent vote, rather than
only counting votes within the 24-hour window. This fix uses Django's
conditional aggregation (filter=Q(...)) to correctly count and find the
max cast_at only for votes within the cutoff period.

Also adds .distinct() to prevent duplicate elections in results and
improves code readability by extracting the cutoff to a variable.
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR optimizes the database query in the recent_votes admin view by using Django's conditional aggregation feature to ensure that aggregated values (count and max) only consider votes within the 24-hour cutoff period, rather than all votes for elections that happen to have at least one recent vote.

Changes:

  • Added Q import from django.db.models for conditional filtering in aggregations
  • Extracted cutoff calculation into a variable for better readability and DRY principle
  • Added .distinct() to prevent duplicate election records from JOIN operations
  • Applied filter=Q(...) parameter to both Max() and Count() aggregations to ensure only recent votes are considered

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@benadida benadida merged commit c3fdde9 into master Jan 20, 2026
7 checks passed
@benadida benadida deleted the claude/optimize-votes-query-PHzxO branch January 20, 2026 12:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants