Mat*_*non 21 javascript python django json d3.js
我正在尝试使用Django和D3.js编写一个非常基本的条形图.我有一个名为play的对象,其日期时间字段名为date.我想要做的是显示按月分组的游戏数量.基本上我有两个问题:
现在我在这里看了一些其他的答案,并尝试过
json = (Play.objects.all().extra(select={'month': "extract(month FROM date)"})
.values('month').annotate(count_items=Count('date')))
Run Code Online (Sandbox Code Playgroud)
这接近我想要的信息但是当我尝试在模板中输出它时,它在月末出现如下(带Ls).这意味着显然它不是有效的js(没有qoutes)而且我真的不希望Ls到底那里.
模板:
<script>
var test ={{ json|safe }};
alert("test");
</script>
Run Code Online (Sandbox Code Playgroud)
输出:
var test = [{'count_items': 10, 'month': 1L}, {'count_items': 5, 'month': 2L}];
Run Code Online (Sandbox Code Playgroud)
我也尝试过这个数据的json.dump,但我被告知它是无效的JSON.这感觉在Django中应该更直接,所以也许我完全走向了这条路.
Fer*_*edo 66
由于D3.js v3有很多方法可以从外部资源中加载数据 ¹,最好不要将数据嵌入到页面中,只需加载它即可.
这将是一个例子的答案.
让我们从模型定义开始:
# models.py
from django.db import models
class Play(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()
Run Code Online (Sandbox Code Playgroud)
一个urlconf:
# urls.py
from django.conf.urls import url
from .views import graph, play_count_by_month
urlpatterns = [
url(r'^$', graph),
url(r'^api/play_count_by_month', play_count_by_month, name='play_count_by_month'),
]
Run Code Online (Sandbox Code Playgroud)
我们使用两个url,一个用于返回html(视图graph),另一个url(视图play_count_by_month)用作api,仅返回数据为JSON.
最后我们的意见:
# views.py
from django.db import connections
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render
from .models import Play
def 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)
Run Code Online (Sandbox Code Playgroud)
在这里,我们定义了一个视图,将我们的数据作为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>
Run Code Online (Sandbox Code Playgroud)
这将返回一个像这样的好图(随机数据):

更新1:D3 v4将移动代码以将外部数据加载到专用库,请参阅d3-request. 更新2:为了提供帮助,我将所有文件放在一个示例项目中,在github上:github.com/fgmacedo/django-d3-example
| 归档时间: |
|
| 查看次数: |
27369 次 |
| 最近记录: |