views.py是
def index(request):
fm_ds=Details.objects.filter(Gender='Female',Dept='Software',Shift='Day').count()
m_ds=Details.objects.filter(Gender='Male',Dept='Software',Shift='Day').count()
Female_dict={}
Female_dict['Gender']='Female'
Female_dict['count']=fm_ds
Male_dict={}
Male_dict['Gender']='Male'
Male_dict['count']=m_ds
print Female_dict
print Male_dict
di=[Male_dict,Female_dict]
context = {'data_json': json.dumps(di)}
print context
return render(request, 'index.html', context=context)
输出为:[{'count': 1, 'Gender': 'Male'}, {'count': 2, 'Gender': 'Female'}]
现在我需要将这个json传递给d3.js模板来绘制这种link的图形。在x轴上是feMALE,在y轴上是指数。
index.html是
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
.bar { fill: steelblue; }
</style>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scaleBand()
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.range([height, 0]);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// get the data
var data_json = {{ data_json|safe }};
var data=[];
data.push(temp);
x.domain(data.map(function(d) { return d.gender; }));
y.domain([0, d3.max(data, function(d) { return d.count; })]);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.gender); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.count); })
.attr("height", function(d) { return height - y(d.count); });
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
</script>
</body>
我只得到他们的计数的男/女图...不是两个!
答案 0 :(得分:0)
我试过这个并在index.html中得到答案
<script>
var temp = {{ data_json|safe }};
var data=[]
data.push(temp);
console.log(JSON.stringify(data))
</script>