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

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

我想从我的模型中获得一个图表报告,但我不知道如何使用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%}

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

r9f1avp5

r9f1avp51#

您可以尝试:

...
data: {
                            labels: [{%for data in dictCategory%} {{ data.category }}, {%endfor%}] //loop through queryset, 
                            datasets: [{
                                label: '# of users',
                                data: [{%for data in dictCategory%}{{ data.count }},{%endfor%}],
...

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

...
$(document).ready(function(){
                    dictCategory = {{dictCategory}}
                    labels = []
                    data = []
                    for (i = 0; i < dictCategory.length; i++){
                        labels.append(item.category);
                        data.append(item.count);
                    }
                    var ctx = document.getElementById('myChart').getContext('2d');
                    var myChart = new Chart(ctx, {
                        type: 'doughnut',
                        data: {
                            labels: labels, 
                            datasets: [{
                                label: '# of users',
                                data: data
...
slsn1g29

slsn1g292#

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

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

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

<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 category_list %} '{{data}}', {% endfor %}],
                datasets: [{
                    label: '# of categories',
                    data: [{% for data in count_list %}{{data}},{% 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)',
                        'rgba(54, 162, 64, 0.2)',
                        'rgba(255, 148, 64, 0.2)',
                        'rgba(75, 175, 192, 0.2)',
                        'rgba(255, 130, 64, 0.2)',
                        'rgba(54, 158, 64, 0.2)',
                        'rgba(255, 125, 64, 0.2)',
                        'rgba(75, 165, 192, 0.2)'
                    ],
                    borderWidth: 1
                }]
            },
        });
    });
    </script>

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

相关问题