您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将数据从Django传递到D3

将数据从Django传递到D3

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

我们使用两个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)

在这里,我们定义了一个视图以将数据返回为JSON,请注意,由于我使用sqlite进行了测试,因此我做了一些更改,使其与数据库无关。

并遵循我们的·模板,该模板显示按月播放的图表:

<!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"
Go 2022/1/1 18:22:35 有325人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶