由于D3.js v3提供了很好的方法集合,可从外部资源 ¹
加载数据,因此最好不要将数据嵌入到页面中,而只需加载它即可。
这将是一个示例答案。
让我们从模型定义开始:
# models.pyfrom django.db import modelsclass Play(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField()
urlconf:
# urls.pyfrom django.conf.urls import urlfrom .views import graph, play_count_by_monthurlpatterns = [ url(r'^$', graph), url(r'^api/play_count_by_month', play_count_by_month, name='play_count_by_month'),]
我们使用两个URL,一个返回html(视图
graph),另一个使用url(视图
play_count_by_month)作为api,仅以JSON形式返回数据。
最后是我们的观点:
# views.pyfrom django.db import connectionsfrom django.db.models import Countfrom django.http import JsonResponsefrom django.shortcuts import renderfrom .models import Playdef graph(request): return render(request, 'graph/graph.html')def play_count_by_month(request): data = Play.objects.all() .extra(select={'month': connections[Play.objects.db].ops.date_trunc_sql('month', 'date')}) .values('month') .annotate(count_items=Count('id')) return JsonResponse(list(data), safe=False)在这里,我们定义了一个视图以将数据返回为JSON,请注意,由于我使用SQLite进行了测试,因此我做了一些更改,使其与数据库无关。
并遵循我们的
graph/graph.html模板,该模板显示按月播放的图表:
<!DOCTYPE html><meta charset="utf-8"><style>body { font: 10px sans-serif;}.axis path,.axis line { fill: none; stroke: #000; shape-rendering: crispEdges;}.x.axis path { display: none;}.line { fill: none; stroke: steelblue; stroke-width: 1.5px;}</style><body><script src="http://d3js.org/d3.v3.js"></script><script>var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom;var parseDate = d3.time.format("%Y-%m-%d").parse; // for dates like "2014-01-01"//var parseDate = d3.time.format("%Y-%m-%dT00:00:00Z").parse; // for dates like "2014-01-01T00:00:00Z"var x = d3.time.scale() .range([0, width]);var y = d3.scale.linear() .range([height, 0]);var xAxis = d3.svg.axis() .scale(x) .orient("bottom");var yAxis = d3.svg.axis() .scale(y) .orient("left");var line = d3.svg.line() .x(function(d) { return x(d.month); }) .y(function(d) { return y(d.count_items); });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 + ")");d3.json("{% url "play_count_by_month" %}", function(error, data) { data.forEach(function(d) { d.month = parseDate(d.month); d.count_items = +d.count_items; }); x.domain(d3.extent(data, function(d) { return d.month; })); y.domain(d3.extent(data, function(d) { return d.count_items; })); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Play count"); svg.append("path") .datum(data) .attr("class", "line") .attr("d", line);});</script></body></html>这将返回一个漂亮的图形,如下所示(随机数据):
更新1 :D3
v4将移动代码以将外部数据加载到专用库中,请参阅d3-request。
更新2
:为了提供帮助,我将所有文件放到github上的示例项目中:github.com/fgmacedo/django-d3-example



