一招实现Django API为D3提供数据
在Python开发工作中见过有的人即便使用了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 renderfrom .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部分
1
2
3
27
28
93
94
输出结果,大家可以在admin里调整数据。
文章来自:https://www.itjmd.com/news/show-5334.html