# HG changeset patch # User Brian Neal # Date 1462841331 18000 # Node ID 71685387dd11752f6216463b0c9273b3911b7e75 # Parent 64fb0d6933a4da2145fecc9ebed3b738ce39082c Reduce database usage on poll index page. diff -r 64fb0d6933a4 -r 71685387dd11 polls/views.py --- a/polls/views.py Sun May 08 21:03:09 2016 -0500 +++ b/polls/views.py Mon May 09 19:48:51 2016 -0500 @@ -36,8 +36,28 @@ ####################################################################### def poll_index(request): - current_polls = Poll.objects.get_current_polls() - old_polls = Poll.objects.get_old_polls() + + # Do some stuff manually to avoid cascading hits to the database + now = datetime.datetime.now() + qs = Poll.objects.filter(is_enabled=True) + poll_dict = {} + current_polls = [] + old_polls = [] + for poll in qs: + poll.total_votes_ = 0 + poll_dict[poll.pk] = poll + if (poll.start_date <= now and + (poll.end_date is None or poll.end_date >= now)): + current_polls.append(poll) + elif (poll.start_date < now and + (poll.end_date is not None and poll.end_date < now)): + old_polls.append(poll) + + for choice in Choice.objects.iterator(): + poll = poll_dict.get(choice.poll_id) + if poll: + poll.total_votes_ += choice.votes + return render(request, 'polls/index.html', { 'current_polls': current_polls, 'old_polls': old_polls, diff -r 64fb0d6933a4 -r 71685387dd11 sg101/templates/polls/index.html --- a/sg101/templates/polls/index.html Sun May 08 21:03:09 2016 -0500 +++ b/sg101/templates/polls/index.html Mon May 09 19:48:51 2016 -0500 @@ -8,9 +8,7 @@