Mercurial > public > sg101
changeset 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 | 64fb0d6933a4 |
children | f7554fb88727 |
files | polls/views.py sg101/templates/polls/index.html |
diffstat | 2 files changed, 24 insertions(+), 8 deletions(-) [+] |
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,
--- 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 @@ <ul> {% for poll in current_polls %} <li><a href="{{ poll.get_absolute_url }}">{{ poll.question }}</a> • - {{ poll.total_votes }} vote{{ poll.total_votes|pluralize }} • - {% get_comment_count for poll as comment_count %} - {{ comment_count }} comment{{ comment_count|pluralize }} • + {{ poll.total_votes_ }} vote{{ poll.total_votes_|pluralize }} • {{ poll.start_date|date:"M d, Y" }} {% if poll.end_date %} - {{ poll.end_date|date:"M d, Y" }} @@ -26,9 +24,7 @@ <ul> {% for poll in old_polls %} <li><a href="{{ poll.get_absolute_url }}">{{ poll.question }}</a> • - {{ poll.total_votes }} vote{{ poll.total_votes|pluralize }} • - {% get_comment_count for poll as comment_count %} - {{ comment_count }} comment{{ comment_count|pluralize }} • + {{ poll.total_votes_ }} vote{{ poll.total_votes_|pluralize }} • {{ poll.start_date|date:"M d, Y" }} - {{ poll.end_date|date:"M d, Y" }}</li> {% endfor %}