django admin simplepro首页图表教程
2022年7月5日大约 2 分钟约 609 字
SimplePro 首页图表
SimplePro 首页图表请求URL BUG
SimplePro 使用首页图表时,请求URL路径中类似与 /static//
,后面多了一个斜杠,使用中间件修改后可以正常使用。
utils/app/middlewares.py
from django.http import HttpResponseRedirect
class RedirectSpBawaMiddleware:
"""BUG修复 SimplePro 主页图表功能请求URL报错问题。
将 /sp/bawa/ 301重定向到 /static/admin/bawa/
可能是 simplepro.middlewares.SimpleMiddleware 中间件代码问题
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.path.startswith('/sp/bawa/charts/'):
new_path = request.path.replace('/sp/bawa/charts/', '/static/admin/bawa/charts/')
return HttpResponseRedirect(new_path)
elif request.path.startswith('/sp/bawa/echarts/'):
new_path = request.path.replace('/sp/bawa/echarts/', '/static/admin/bawa/echarts/')
return HttpResponseRedirect(new_path)
response = self.get_response(request)
return response
conf/settings.py
MIDDLEWARE = [
# ...
'utils.app.middlewares.RedirectSpBawaMiddleware', # SimplePro 图表请求URL地址 BUG修复
'simplepro.middlewares.SimpleMiddleware',
]
SimplePro 图表数据视图示例
app/charts/views
from django.views import View
from django.http import JsonResponse
from django.db.models import Count
from children.models import ChildModel
from django.db.models.functions import TruncDate
from women.models import WomanModel
class CalendarView(View):
"""日历图数据。获取每日的儿童与妈妈绑定的数量"""
def get(self, request):
# 获取默认的中间表模型
through_model = WomanModel.children.through
# 获取绑定关系数据并按日期统计
bindings = through_model.objects.annotate(date=TruncDate('create_time')).values('date').annotate(count=Count('id')).order_by('date')
# 转换数据格式
# data = [
# {
# "date": binding['date'].strftime("%Y-%m-%d"),
# "commits": binding['count'],
# "month": binding['date'].month - 1, # JavaScript中的月份从0开始
# "day": binding['date'].day,
# "week": binding['date'].strftime("%w") # 获取星期几,0是星期天
# }
# for binding in bindings
# ]
#
data = [
{
"date": '2017-05-01',
"commits": 1,
"month": 4,
"day": 1,
"week": '0'
},
]
return JsonResponse(data, safe=False)
class MapView(View):
"""地图数据"""
def get(self, request):
data_type = request.GET.get('type')
# 使用 Django ORM 的 annotate 和 values 方法来进行聚合查询
if data_type == 'no_bind': # 统计各区未被绑定的儿童数量
area_counts = ChildModel.objects.filter(womanmodel__isnull=True).values('area').annotate(count=Count('area'))
else: # 统计各区所有儿童数量
area_counts = ChildModel.objects.values('area').annotate(count=Count('area'))
area_data = [{'name': item['area'], 'value': item['count']} for item in area_counts]
return JsonResponse(area_data, safe=False)
class GraphView(View):
"""关系图数据"""
def get(self, request):
# 获取所有妈妈和儿童的关系数据
women = WomanModel.objects.prefetch_related('children').all()
# 准备节点和边的数据
nodes = []
links = []
node_set = set()
# 添加妈妈节点
for woman in women:
if woman.id not in node_set:
nodes.append({
'id': f'w_{woman.id}',
'name': woman.name,
'category': 0,
'symbolSize': 20,
'value': len(woman.children.all())
})
node_set.add(woman.id)
# 添加与妈妈相关的儿童节点和边
for child in woman.children.all():
if child.id not in node_set:
nodes.append({
'id': f'c_{child.id}',
'name': child.name,
'category': 1,
'symbolSize': 10,
'value': 1,
'itemStyle': {'color': '#336699'}
})
node_set.add(child.id)
links.append({
'source': f'w_{woman.id}',
'target': f'c_{child.id}'
})
categories = [{'name': '妈妈'}, {'name': '儿童'}]
data = {
'nodes': nodes,
'links': links,
'categories': categories
}
return JsonResponse(data, safe=False)