在工作中见过有的人即便使用了Django,依然还在采取json或geojson的文件形式为页面提供数据,相当于嵌入数据而非加载。下面是个简单有效的例子:

先从 model.py 开始

 # models.py
from django.db import models class Play(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()

urls.py 建立一个 API 的数据(JSON格式)输出路径,另一个给图像输出页面。

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

views.py

# 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)

下面则是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>

输出结果,大家可以在admin里调整数据。

Django API 为 D3 提供数据的更多相关文章

  1. Django API验证(令牌)

    1. 获取接口信息 Client端 import requests import time import hashlib ctime = time.time() key = 'akfljakfjakl ...

  2. Django API接口FK ManyTo Many 模板

    Url from django.contrib import admin from django.urls import path, re_path from django.urls import i ...

  3. Django API view 登录认证

    文件分类 url from django.contrib import admin from django.urls import path, re_path from django.urls imp ...

  4. 【AMAD】django-formapi -- 一个DJANGO API框架,可使用签名request,可使用form作为API的验证工具

    动机 简介 个人评分 动机 如何快速构建API,使用view就行了? 如果快速构建一个可以验证参数的API,使用django-formapi1吧! 简介 class DivisionCall(call ...

  5. Django api

    http://www.cnblogs.com/wulaoer/p/5276050.html

  6. Django API 自定义状态码

    class BaseResponse(object): def __init__(self): self.code = 1000 self.data = None self.error = None ...

  7. django API返回中文乱码

    renturn HttpResponse(json.dumps(data,ensure_ascii=False))

  8. 初识Django —Python API接口编程入门

    初识Django —Python API接口编程入门 一.WEB架构的简单介绍 Django是什么? Django是一个开放源代码的Web应用框架,由Python写成.我们的目标是用Python语言, ...

  9. 【Django】ESRTful APi

    如何利用rest framework搭建Django API框架!   环境:win10 python3.6 思路步骤: 创建一个可以序列化的类 去数据库取数据交给序列化的类处理 把序列化的数据返回前 ...

随机推荐

  1. Spark Mllib里相似度度量(基于余弦相似度计算不同用户之间相似性)(图文详解)

    不多说,直接上干货! 常见的推荐算法 1.基于关系规则的推荐 2.基于内容的推荐 3.人口统计式的推荐 4.协调过滤式的推荐 协调过滤算法,是一种基于群体用户或者物品的典型推荐算法,也是目前常用的推荐 ...

  2. 八个cmd 命令

    一,ping 它是用来检查网络是否通畅或者网络连接速度的命令.作为一个生活在网络上的管理员或者黑客来说,ping命令是第一个必须掌握的DOS命令,它所利用的原理是这样的:网络上的机器都有唯一确定的IP ...

  3. java之struts框架入门教程

    本教程主要讲述struts的简单入门操作 使用的是myeclipse工具 1.创建web项目 2.复制struts必要的jar包到 WebRoot/WEB-INF/lib 下 jar包列表如下: as ...

  4. Java中的while循环——通过示例学习Java编程(10)

    作者:CHAITANYA SINGH 来源:https://www.koofun.com/pro/kfpostsdetail?kfpostsid=20 在上一个教程中,我们讨论了for循环的用法.在本 ...

  5. 转载:Maven实战—Dependencies与DependencyManagement的区别

    致敬作者,支持原创.原文地址:https://www.cnblogs.com/feibazhf/p/7886617.html 在上一个项目中遇到一些Jar包冲突的问题,之后还有很多人分不清楚Depen ...

  6. js和jq获取父,兄弟,子节点

    1,js获取节点: 父: parentNode 获取已知节点的父节点. 子: childNodes; 得到全部子节点 children 得到全部子节点 firstChild 获得第一个子节点 last ...

  7. Android中渐变图片失真的解决方案

    在android开发(尤其是android游戏开发)中有一个很严重的问题就是带有渐变效果的png图片会出现严重的banding(色带),鉴于这种情况,有几种可行的解决方法:   1.如果Activit ...

  8. django Q条件

    #q条件from django.db.models import Qq = Q(name__startswith="p") | Q(name__startswith="l ...

  9. mstsc远程桌面全频或自定义窗口

    近期发现自己的mstsc突然窗口变小,总是要繁琐的拖来拖去,现终于解决了,拿来分享一二! 参数一:mstsc /f   以全屏模式显示(操作一次,后面无需在设置,具体何原因要问微软了,可能是机器的分辨 ...

  10. python+selenium之自动生成excle,保存到指定的目录下

    进行之自动化测试,想把自动生成的excle保存到指定的目录下.网上百度的代码如下: import xlwt import time time = time.strftime ('%Y%m%d%H%M% ...