一招实现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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值