我正在尝试构建我的数据以在饼图中显示。
我有一个带有布尔列的表:根,骨,沉积物。
我可以将数据过滤到字典中(在views.py中):
a = Fraction.objects.values('roots').filter(roots=True)
b = Fraction.objects.values('bone').filter(bone=True)
c = Fraction.objects.values('sediment').filter(sediment=True)
dataset4 = {"roots": a, "bone": b, "sediment": c}
它返回'dataset4': dataset4,
在html highchart代码中我通常添加数据:
#views.py
dataset4 = Fraction.objects.values('roots')
#html
<script>
Highcharts.chart('container4', {
chart: {type: 'pie'},
title: {text: 'Sample Remains'},
credits: {enabled: false},
xAxis: {
categories: [
{% for entry in dataset4 %}'C {{ entry.roots }}'{% if not forloop.last %}, {% endif %}{% endfor %}
]
},
series: [{
name: 'Botany Records',
data: [
{% for entry in dataset4 %}
{{ entry.roots }}
{% if not forloop.last %},
{% endif %}
{% endfor %}
],
color: 'green'
}]
如何传递字典对象而不是查询集?
您需要修改查询以获取根,骨骼和沉积物的总计数,然后将这些计数传递给模板:
a = Fraction.objects.filter(roots=True).count()
b = Fraction.objects.filter(bone=True).count()
c = Fraction.objects.filter(sediment=True).count()
dataset4 = {"roots": a, "bone": b, "sediment": c}
然后在模板中,您应该能够通过迭代字典中的每个项来为系列创建数据,例如:
series: [{
name: 'Botany Records',
data: [
{% for name, count in dataset4.items %}
{name: '{{ name }}', y: {{ count }} }
{% if not forloop.last %},{% endif %}
{% endfor %}
],
color: 'green'
}]