여론조사 결과보기3 - Dictionary로 데이터 정리
주의 [여론조사 결과보기2]와 Choice
모델 필드가 달라졌습니다.
하단에 강의에서 쓰인 views.py와 [여론조사 결과보기2]에 Choice
모델에서 쓸 수 있는 views.py 를 함께 적어놓았으니, 두번째 views.py를 써 주세요.
별도의 마이그레이션 없이 첫번째 views.py를 쓸 경우 모든 rates가 0으로 설정됩니다.
# C:\Code\mysite\elections\views.py
# 강의에서 쓰인 views.py
from django.db.models import Sum
# 기존 코드 유지
def results(request, area):
candidates = Candidate.objects.filter(area = area)
polls = Poll.objects.filter(area = area)
poll_results = []
for poll in polls:
result = {}
result['start_date'] = poll.start_date
result['end_date'] = poll.end_date
# poll.id에 해당하는 전체 투표수
total_votes = Choice.objects.filter(poll_id = poll.id).aggregate(Sum('votes'))
result['total_votes'] = total_votes['votes__sum']
rates = [] #지지율
for candidate in candidates:
# choice가 하나도 없는 경우 - 예외처리로 0을 append
try:
choice = Choice.objects.get(poll_id = poll.id, candidate_id = candidate.id)
rates.append(
round(choice.votes * 100 / result['total_votes'], 1)
)
except :
rates.append(0)
result['rates'] = rates
poll_results.append(result)
context = {'candidates':candidates, 'area':area,
'poll_results' : poll_results}
return render(request, 'elections/result.html', context)
# C:\Code\mysite\elections\views.py
# 여론조사 결과보기2에 Contact모델과 이어지는 views.py
def results(request, area):
candidates = Candidate.objects.filter(area = area)
polls = Poll.objects.filter(area = area)
poll_results = []
for poll in polls:
result = {}
result['start_date'] = poll.start_date
result['end_date'] = poll.end_date
# poll.id에 해당하는 전체 투표수
total_votes = Choice.objects.filter(poll_id = poll.id).aggregate(Sum('votes'))
result['total_votes'] = total_votes['votes__sum']
rates = [] #지지율
for candidate in candidates:
# choice가 하나도 없는 경우 - 예외처리로 0을 append
try:
choice = Choice.objects.get(poll = poll, candidate = candidate)
rates.append(
round(choice.votes * 100 / result['total_votes'], 1)
)
except :
rates.append(0)
result['rates'] = rates
poll_results.append(result)
context = {'candidates':candidates, 'area':area,
'poll_results' : poll_results}
return render(request, 'elections/result.html', context)
<!-- C:\Code\mysite\elections\templates\elections\result.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{area}} 여론조사 결과</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>{{area}}</h1>
<br>
<table class="table table-striped">
<thead>
<tr>
<td><B>기간</B></td>
{% for candidate in candidates %}
<td><B>{{candidate.name}}</B></td>
{% endfor %}
</tr>
</thead>
<tbody>
{% for result in poll_results %}
<tr>
<td> {{result.start_date.year}}/{{result.start_date.month}}/{{result.start_date.day}}~{{result.end_date.year}}/{{result.end_date.month}}/{{result.end_date.day}} </td>
{% for rate in result.rates %}
<td> {{rate}}%</td>
{% endfor %}
</tr>
<tbody>
{% endfor %}
</table>
</div>
</body>
-
저는 이상하게 .objects.get부분이 안먹네요.
위대연
2018.7.10 16:31
0
-
두 개의 views.py가 어떻게 다른건지 모르겠어요
-
2018.7.6 20:41
0
-
하나의 area에 여러개의 poll을 등록했을 때 오류
이상락
2018.2.14 17:24
0
-
admin에서 새로운 Poll object 등록 문제
-
2017.7.31 23:20
2
-
강의 노트에 오타가 있습니다.
-
2016.11.6 15:14
1
-
강의자료에 나와있는 데로 했는데요..... 힐러리와 트럼프가 모두 0%로 출력되요
-
2016.8.1 15:41
1
-
강의와 노트의 코드 차이점
-
2016.7.21 17:47
1
-
질문이요
-
2016.5.31 21:38
1
-
투표수가 힐러리, 트럼프 둘다 0으로 나와요
-
2016.5.18 22:27
2