我想从我的模型中获得一个图表报告,但我不知道如何使用chart.js将数据从字典传递到图表?
这是我的模型:
class Book(models.Model):
number = models.CharField(_("number"), max_length=255)
title = models.CharField(_("title"), max_length=255)
subtitle = models.CharField(_("subtitle"), max_length=255, null=True,)
authors = models.TextField(_("authors"), null=True,)
publisher = models.CharField(_("publisher"), max_length=255, null=True,)
published_date = models.DateField(_("published date"), null=True,)
category = models.CharField(_("category"), max_length=255, null=True,)
distrubution_expense = models.FloatField(_("distribution expense"))
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('book_detail', args=[str(self.id)])
这是我的观点,我使用queryset来计算类别重复的数量:
class CategoryChartListView(generic.ListView):
model = Book
template_name= 'pages/chart_category.html'
def get_context_data(self, **kwargs):
context = super(CategoryChartListView, self).get_context_data(**kwargs)
context["dictCategory"] = Book.objects.values('category').annotate(count=Count('category'))
return context
这也是我从上面的queryset视图中获得的字典:
{'category': 'Business Analytics', 'count': 336}
{'category': 'Data ethics', 'count': 389}
{'category': 'visualization', 'count': 314}
{'category': 'statistics', 'count': 428}
{'category': 'NLP', 'count': 368}
{'category': 'Language', 'count': 1}
{'category': 'python', 'count': 373}
{'category': 'maths', 'count': 379}
{'category': 'deep learning', 'count': 364}
{'category': 'SQL', 'count': 403}
{'category': 'Python', 'count': 80}
{'category': 'R Studio', 'count': 246}
{'category': 'data science', 'count': 395}
{'category': None, 'count': 0}
模板:
{%block content%}
<!-- displaying the chart -->
<!-- you can also play around with the width and height to increase or decrease the chart size -->
<canvas id="myChart" width="400" height="100"></canvas>
{%endblock content%}
{%block scripts%}
<script>
// jquery function
$(document).ready(function(){
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [{%for data in dictCategory%} {{ data.keys }}, {%endfor%}] //loop through queryset,
datasets: [{
label: '# of users',
data: [{%for data in dictCategory%}{{ data.values }},{%endfor%}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
});
</script>
{%endblock scripts%}
我使用这些代码,但我什么也没有得到。
2条答案
按热度按时间r9f1avp51#
您可以尝试:
问题是这里的键是category和count,值是它们的值。所以当你试图得到密钥时,你会得到
category
和count
。另一种方法是:
slsn1g292#
我没有找到将“dictCategory”字典传递给chart.js的方法。所以我把它转换成两个列表:
然后我在chart.js中使用它们:
它工作了:[1]:https://i.stack.imgur.com/9hVuO.png