Django 2.0适配w2ui 1.5 Grid:如何格式化查询结果
适配w2ui Grid的Django查询结果格式转换方案
问题背景
我正在使用Django 2.0和w2ui 1.5 Grid,希望将查询结果展示在w2ui的数据网格中。w2ui数据网格要求的JSON结构如下:
{"status": "success", "total": 1, "records": [{"key": "value", "key2": "value2"} ]}
我的views.py代码如下(因查询语句复杂,使用cursor实现):
from django.db import connection cursor = connection.cursor() query=("select table1.id as id,table1.code as code,table1.nom as nom,table2.nom as tgen\ from table1, table2\ where table1.table2_id = table2.id\ EXCEPT\ select table1.id,table1.code,table1.nom,table2.nom\ from table1,table2\ where table1.table2_id = table2.id\ and table1.id in (select table1_id\ from table3\ where table3.id in (select table3_id\ from table4))") cursor.execute(query) result = [ dict(line) for line in [zip([ column[0] for column in cursor.description], row) for row in cursor.fetchall()] ]
当前result的输出为:
[{"id": 1, "nom": "jojo", "typegen": "aloba", "code": "GEN-1"} ]
请问如何为该结果添加{"status": "success"}和{"total":1},使其适配w2ui数据网格的展示要求?
解决方案
其实这事儿很简单,你只需要把现有的result包装到一个新字典里,同时补上status和total两个字段就行,而且有更灵活的写法不用硬写数字。
1. 构造符合要求的响应结构
在生成result之后,直接创建一个符合w2ui格式的字典:
# 生成result之后添加这段代码 w2ui_response = { "status": "success", "total": len(result), # 自动获取记录条数,不用手动写1,适配任意结果数量 "records": result }
这样w2ui_response就完全满足w2ui Grid的要求了,接下来用Django的JsonResponse把它返回给前端就行:
from django.http import JsonResponse # 在视图函数末尾返回响应 return JsonResponse(w2ui_response)
2. 可选优化:简化result生成代码
你的result生成代码可以简化一下,可读性会更好,功能完全不变:
# 替换原来的result生成代码 columns = [col[0] for col in cursor.description] result = [dict(zip(columns, row)) for row in cursor.fetchall()]
内容的提问来源于stack exchange,提问作者Hervé
相关产品推荐
相关产品推荐

