diff --git a/helios/stats_views.py b/helios/stats_views.py index 0902bea46..6b2c3d636 100644 --- a/helios/stats_views.py +++ b/helios/stats_views.py @@ -6,7 +6,7 @@ from django.core.paginator import Paginator from django.urls import reverse -from django.db.models import Max, Count +from django.db.models import Max, Count, Q from django.http import HttpResponseRedirect from django.views.decorators.http import require_http_methods @@ -56,10 +56,16 @@ def elections(request): def recent_votes(request): user = require_admin(request) - + # elections with a vote in the last 24 hours, ordered by most recent cast vote time # also annotated with number of votes cast in last 24 hours - elections_with_votes_in_24hours = Election.objects.filter(voter__castvote__cast_at__gt= datetime.datetime.utcnow() - datetime.timedelta(days=1)).annotate(last_cast_vote = Max('voter__castvote__cast_at'), num_recent_cast_votes = Count('voter__castvote')).order_by('-last_cast_vote') + cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=1) + elections_with_votes_in_24hours = Election.objects.filter( + voter__castvote__cast_at__gt=cutoff + ).distinct().annotate( + last_cast_vote=Max('voter__castvote__cast_at', filter=Q(voter__castvote__cast_at__gt=cutoff)), + num_recent_cast_votes=Count('voter__castvote', filter=Q(voter__castvote__cast_at__gt=cutoff)) + ).order_by('-last_cast_vote') return render_template(request, "stats_recent_votes", {'elections' : elections_with_votes_in_24hours})