2014-10-19 54 views
16

我想用Django和D3.js編寫一個非常基本的條形圖。我有一個名爲date的日期時間字段叫做play的對象。我想要做的是顯示按月份分組的時間段數。基本上,我有兩個問題:將數據從Django傳遞到D3

  1. 我如何獲得這些分組通過一個月的播放次數的計數當月
  2. 什麼是擺脫Django的這一信息納入由D3使用的東西的最佳方式。

現在我已經看了看這裏的一些其他的答案,並試圖

json = (Play.objects.all().extra(select={'month': "extract(month FROM date)"}) 
.values('month').annotate(count_items=Count('date'))) 

這得到接近我想要trhe信息,但是當我嘗試在模板輸出它弄出來,如下(含Ls)在月末。這意味着顯然它不是有效的js(沒有qoutes),並且我也不是真的想要Ls到最後。

模板:

<script> 
     var test ={{ json|safe }}; 
     alert("test"); 

    </script> 

輸出:

var test = [{'count_items': 10, 'month': 1L}, {'count_items': 5, 'month': 2L}]; 

我自己也嘗試在這個數據json.dumps,但我得到告訴這不是有效的JSON。這讓我覺得在Django中應該更直截了當,所以我可能會完全走向蠕蟲路徑。

+0

您使用的是Django 1.7嗎?我已經爲您定製了一個解決方案,只是爲了驗證我們使用的是相同的版本。 – 2014-10-19 21:31:05

+0

1.4.1我們說話時升級,然後我會試試你的答案。 – 2014-10-19 21:53:50

+0

好的。這是因爲[django.http.JsonResponse](https://docs.djangoproject.com/zh/dev/ref/request-response/#jsonresponse-objects)是在1.7版本中引入的。 – 2014-10-19 21:58:06

回答

47

因爲D3.js v3有很好的收集methods to load data from external resources¹,所以最好不要將數據嵌入到您的頁面中,您只需加載它。

這將是一個例子的答案。

讓我們先從一個模型定義:

# models.py 
from django.db import models 


class Play(models.Model): 
    name = models.CharField(max_length=100) 
    date = models.DateTimeField() 

URL配置:

# 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'), 
] 

我們使用兩個網址,一個返回HTML(查看),以及其他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) 

在這裏,我們定義的視圖來回報廣大的數據作爲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> 

這將返回一個不錯的圖形像這樣(隨機數據): Graph of Play counts by month

更新1: D3 v4將移動代碼以將外部數據加載到專用庫,請參閱d3-request更新2:爲了提供幫助,我已將所有文件放在一個示例項目中,在github上:github.com/fgmacedo/django-d3-example

+0

嗯,所以我嘗試把所有這些放在一起,我得到的是圖的左側部分(沒有行或標籤)。這裏是我的play_count_by_month頁面輸出的樣子: '[{「count_items」:10,「month」:「2013-01-01T00:00:00Z」},{「count_items」:5,「month」:「 2013-02-01T00:00:00Z「}]' 我沒有在網絡端看到任何JS錯誤或任何問題(看起來好像讓請求正常) – 2014-10-20 00:08:57

+1

日期格式有問題。 'play_count_by_month'的結果如下:'[{「count_items」:731,「month」:「2014-01-01」},{「count_items」:404,「month」:「2014-02-01」 }]'。您可以嘗試將graph.html上的'parseDate'函數更改爲:'var parseDate = d3.time.format(「%Y-%m-%dT00:00:00Z」)。parse;' – 2014-10-20 00:33:40

+0

工作正常!非常感謝。 – 2014-10-20 05:36:19