问题描述
我正在编写一个samll API,以从数据库中获取(仅GET)数据。
我正在使用没有ModelViewset的APIView,因为结果很复杂且具有很多聚合,因此直接执行sql请求比django ORM更快。
而且我直接将sql响应转换为JSON,而无需使用Django序列化器。
我的问题是:U如何在不使用
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page,many=True)
return self.get_paginated_response(serializer.data)
我的代码示例:
from rest_framework.views import APIView
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from apps.scholl.api import sql_REQUEST
from django.db import connection
class NamesView(APIView):
def get(self,request):
filters = request.data.pop('filters',None)
with connection.cursor() as cursor:
sql_request = sql_REQUEST.format(filters)
cursor.execute(sql_request)
fields_to_show = [f.name for f in cursor.description]
values = cursor.fetchall()
json_res = {}
for key in fields_to_show:
json_resp[f]= []
for index,value in enumerate(values):
if not json_resp.get(fields_to_show[index]):
json_resp[fields_to_show[index]] = []
json_resp[fields_to_show[index]}.append(value)
else:
json_resp[fields_to_show[index]}.append(value)
return Response(json_res)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)