Django と D3.js を使用して、非常に基本的な棒グラフを作成しようとしています。date という日時フィールドを持つ play というオブジェクトがあります。月ごとにグループ化された時間の経過に伴う再生回数を表示したいのです。基本的に 2 つの質問があります。
- 月ごとにグループ化して、その月の再生回数をカウントするにはどうすればよいですか
- この情報を Django から取得して、D3 で使用できる形式に変換する最適な方法は何ですか。
今私はここで他の回答を見て試してみました
json = (Play.objects.all().extra(select={'month': "extract(month FROM date)"})
.values('month').annotate(count_items=Count('date')))
これは私が求めている情報に近づいていますが、テンプレートで出力しようとすると、月の末尾に次の (L を含む) ように出力されます。これは明らかに有効な js (引用符なし) ではないことを意味し、いずれにしても末尾に L は不要です。
テンプレート:
<script>
var test ={{ json|safe }};
alert("test");
</script>
出力:
var test = [{'count_items': 10, 'month': 1L}, {'count_items': 5, 'month': 2L}];
このデータに対して json.dumps も試してみましたが、有効な JSON ではないと言われました。Django ではもっと簡単に実行できるような気がするので、完全に間違った方向に進んでいるのかもしれません。
ベストアンサー1
D3.js v3には素晴らしいコレクションがあるので外部リソースからデータを読み込む方法¹、ページにデータを埋め込まず、読み込むだけにする方がよいでしょう。
これは例による回答になります。
モデルの定義から始めましょう:
# models.py
from django.db import models
class Play(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()
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'),
]
2 つの URL を使用しています。1 つは HTML (view graph
) を返すための URL で、もう 1 つはplay_count_by_month
JSON としてデータのみを返す API としての URL (view) です。
最後に私たちの見解です。
# 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)
ここでは、データを JSON として返すビューを定義しました。SQLite でテストを行ったため、データベースに依存しないように extra を変更したことに注意してください。
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リクエスト。アップデート2: 役に立つように、すべてのファイルを github のサンプル プロジェクトにまとめました。github.com/fgmacedo/django-d3-example