如何在django中将字典数据传递给chart.js?

4szc88ey  于 2023-10-18  发布在  Chart.js
关注(0)|答案(2)|浏览(172)

我想从我的模型中获得一个图表报告,但我不知道如何使用chart.js将数据从字典传递到图表?
这是我的模型:

  1. class Book(models.Model):
  2. number = models.CharField(_("number"), max_length=255)
  3. title = models.CharField(_("title"), max_length=255)
  4. subtitle = models.CharField(_("subtitle"), max_length=255, null=True,)
  5. authors = models.TextField(_("authors"), null=True,)
  6. publisher = models.CharField(_("publisher"), max_length=255, null=True,)
  7. published_date = models.DateField(_("published date"), null=True,)
  8. category = models.CharField(_("category"), max_length=255, null=True,)
  9. distrubution_expense = models.FloatField(_("distribution expense"))
  10. def __str__(self):
  11. return self.title
  12. def get_absolute_url(self):
  13. return reverse('book_detail', args=[str(self.id)])

这是我的观点,我使用queryset来计算类别重复的数量:

  1. class CategoryChartListView(generic.ListView):
  2. model = Book
  3. template_name= 'pages/chart_category.html'
  4. def get_context_data(self, **kwargs):
  5. context = super(CategoryChartListView, self).get_context_data(**kwargs)
  6. context["dictCategory"] = Book.objects.values('category').annotate(count=Count('category'))
  7. return context

这也是我从上面的queryset视图中获得的字典:

  1. {'category': 'Business Analytics', 'count': 336}
  2. {'category': 'Data ethics', 'count': 389}
  3. {'category': 'visualization', 'count': 314}
  4. {'category': 'statistics', 'count': 428}
  5. {'category': 'NLP', 'count': 368}
  6. {'category': 'Language', 'count': 1}
  7. {'category': 'python', 'count': 373}
  8. {'category': 'maths', 'count': 379}
  9. {'category': 'deep learning', 'count': 364}
  10. {'category': 'SQL', 'count': 403}
  11. {'category': 'Python', 'count': 80}
  12. {'category': 'R Studio', 'count': 246}
  13. {'category': 'data science', 'count': 395}
  14. {'category': None, 'count': 0}

模板:

  1. {%block content%}
  2. <!-- displaying the chart -->
  3. <!-- you can also play around with the width and height to increase or decrease the chart size -->
  4. <canvas id="myChart" width="400" height="100"></canvas>
  5. {%endblock content%}
  6. {%block scripts%}
  7. <script>
  8. // jquery function
  9. $(document).ready(function(){
  10. var ctx = document.getElementById('myChart').getContext('2d');
  11. var myChart = new Chart(ctx, {
  12. type: 'doughnut',
  13. data: {
  14. labels: [{%for data in dictCategory%} {{ data.keys }}, {%endfor%}] //loop through queryset,
  15. datasets: [{
  16. label: '# of users',
  17. data: [{%for data in dictCategory%}{{ data.values }},{%endfor%}],
  18. backgroundColor: [
  19. 'rgba(255, 99, 132, 0.2)',
  20. 'rgba(54, 162, 235, 0.2)',
  21. 'rgba(255, 206, 86, 0.2)',
  22. 'rgba(75, 192, 192, 0.2)',
  23. 'rgba(153, 102, 255, 0.2)',
  24. 'rgba(255, 159, 64, 0.2)'
  25. ],
  26. borderColor: [
  27. 'rgba(255, 99, 132, 1)',
  28. 'rgba(54, 162, 235, 1)',
  29. 'rgba(255, 206, 86, 1)',
  30. 'rgba(75, 192, 192, 1)',
  31. 'rgba(153, 102, 255, 1)',
  32. 'rgba(255, 159, 64, 1)'
  33. ],
  34. borderWidth: 1
  35. }]
  36. },
  37. options: {
  38. scales: {
  39. y: {
  40. beginAtZero: true
  41. }
  42. }
  43. }
  44. });
  45. });
  46. </script>
  47. {%endblock scripts%}

我使用这些代码,但我什么也没有得到。

r9f1avp5

r9f1avp51#

您可以尝试:

  1. ...
  2. data: {
  3. labels: [{%for data in dictCategory%} {{ data.category }}, {%endfor%}] //loop through queryset,
  4. datasets: [{
  5. label: '# of users',
  6. data: [{%for data in dictCategory%}{{ data.count }},{%endfor%}],
  7. ...

问题是这里的键是category和count,值是它们的值。所以当你试图得到密钥时,你会得到categorycount
另一种方法是:

  1. ...
  2. $(document).ready(function(){
  3. dictCategory = {{dictCategory}}
  4. labels = []
  5. data = []
  6. for (i = 0; i < dictCategory.length; i++){
  7. labels.append(item.category);
  8. data.append(item.count);
  9. }
  10. var ctx = document.getElementById('myChart').getContext('2d');
  11. var myChart = new Chart(ctx, {
  12. type: 'doughnut',
  13. data: {
  14. labels: labels,
  15. datasets: [{
  16. label: '# of users',
  17. data: data
  18. ...
展开查看全部
slsn1g29

slsn1g292#

我没有找到将“dictCategory”字典传递给chart.js的方法。所以我把它转换成两个列表:

  1. category_list = ['Business Analytics', 'Data ethics',
  2. 'visualization', 'statistics', 'NLP',
  3. 'Language', 'python', 'maths', 'deep
  4. learning', 'SQL', 'Python', 'R
  5. Studio', 'data science']
  6. count_list = [336, 389, 314, 428, 368, 1, 373, 379, 364, 403,
  7. 80, 246, 395]

然后我在chart.js中使用它们:

  1. <script>
  2. // jquery function
  3. $(document).ready(function(){
  4. var ctx = document.getElementById('myChart').getContext('2d');
  5. var myChart = new Chart(ctx, {
  6. type: 'doughnut',
  7. data: {
  8. labels: [{% for data in category_list %} '{{data}}', {% endfor %}],
  9. datasets: [{
  10. label: '# of categories',
  11. data: [{% for data in count_list %}{{data}},{% endfor %}],
  12. backgroundColor: [
  13. 'rgba(255, 99, 132, 0.2)',
  14. 'rgba(54, 162, 235, 0.2)',
  15. 'rgba(255, 206, 86, 0.2)',
  16. 'rgba(75, 192, 192, 0.2)',
  17. 'rgba(153, 102, 255, 0.2)',
  18. 'rgba(255, 159, 64, 0.2)',
  19. 'rgba(54, 162, 64, 0.2)',
  20. 'rgba(255, 148, 64, 0.2)',
  21. 'rgba(75, 175, 192, 0.2)',
  22. 'rgba(255, 130, 64, 0.2)',
  23. 'rgba(54, 158, 64, 0.2)',
  24. 'rgba(255, 125, 64, 0.2)',
  25. 'rgba(75, 165, 192, 0.2)'
  26. ],
  27. borderWidth: 1
  28. }]
  29. },
  30. });
  31. });
  32. </script>

它工作了:[1]:https://i.stack.imgur.com/9hVuO.png

展开查看全部

相关问题