Mercurial > public > sg101
diff polls/views.py @ 1090:71685387dd11
Reduce database usage on poll index page.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Mon, 09 May 2016 19:48:51 -0500 |
parents | ee87ea74d46b |
children | f7554fb88727 |
line wrap: on
line diff
--- 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,