在这里,我试图显示特定年份每个月添加的学生的折线图。但是我在这里有一些小问题。问题出在脚本中。例如,我只在june(1 students)
和july(6 students)
中添加了学生,而在其他月份,学生的数量为zero
。但是在显示june
和july
学生时数字在jan
和feb
月份中。我认为一种解决方案是使脚本中的labels
像{{student.month|date:'F'}},
一样动态,但我想将labels
中的所有12个月都加进去,即使几个月内没有任何学生。我该怎么办?
views.py
def home(request):
students_according_to_month = Student.objects.annotate(month=TruncMonth(F('joined_date'))).values('month')
.annotate(total=Count('pk'))
模板
<script>
/* LINE CHART */
var ctx3 = document.getElementById('chartLine1');
var myChart3 = new Chart(ctx3, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','July','Aug','Sep','Oct','Nov','Dec'],
datasets: [{
label: '# of Votes',
data: [
{% for student in students_according_to_month %}
{{student.total}},
{% endfor %}
],
borderColor: '#dc3545',
borderWidth: 1,
fill: false
}]
},
options: {
legend: {
display: false,
labels: {
display: false
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
fontSize: 10,
max: {{students|length}}
}
}],
xAxes: [{
ticks: {
beginAtZero:true,
fontSize: 11
}
}]
}
}
});
</script>
答案 0 :(得分:0)
进行尽可能高效的数据库查询有多重要?
一种效率稍差的方法是返回每个学生的数据(符合过滤条件?),然后将其重新排列为Python中的每月信息。如果学生人数少于数千,那么这不太可能成为问题。像
query = Student.objects.filter( ... # if you need to filter
).annotate(month=TruncMonth(F('joined_date'))).values_list('month', flat=True)
month_totals = [ 0,0,0,0, 0,0,0,0, 0,0,0,0 ]
for month in query:
# convert month into an integer in range 0-11 if that's not what it is already
# month = map_dict[month]
month_totals[month] += 1
,现在您每个月都有总计,包括那些零学生的月份。将month_totals传递到模板,然后
data: [
{% for total in month_totals %}
{{total}},
{% endfor %}
],