【发布时间】:2019-04-16 01:09:26
【问题描述】:
我正在尝试将 table(来自 Azure 上的远程数据库)中获取的数据分页可以在代码中看到,如下:
import json
import pyodbc
# Includes other imports
def query_db(query):
"""
Function that queries the required table in the DB
"""
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server}; \
SERVER=db.database.windows.net; \
DATABASE=DB; UID=id; PWD=pwd')
cnxn.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')
cur = cnxn.cursor()
cur.execute(query)
# Fetches the entire table ## This is causing the lagg
r = [dict( (cur.description[i][0], value) for i, value in enumerate(row) ) for row in cur.fetchall()]
cur.connection.close()
return(r)
@api_view(['GET'])
def get(request):
paginator = PageNumberPagination()
my_query = query_db("select * from Client_Table")
result_page = paginator.paginate_queryset(my_query, request)
json_output = json.dumps(result_page, cls=DjangoJSONEncoder)
return paginator.get_paginated_response(json_output)
这里的问题是:我首先获取整个表格,然后对其进行分页。我如何分页,而不必获取整个表格? 注意:我没有使用 Django 模型
【问题讨论】:
-
如果是我,我宁愿从远程数据库中获取所有数据并缓存在redis中。
-
有趣的想法(虽然我从未使用过任何缓存库或 Redis)。但是,这将如何工作?我的表中有大约 5000 条记录,每页分页 15 条记录。我会缓存什么(如果我要缓存)?
-
似乎您可能会在运行查询后尝试选择 fetchone() 来查询您想要多少表? docs.djangoproject.com/en/2.2/topics/db/sql/…
-
我认为使用
Model.objects.count()来获取total_page 和Model.objects.all()[:15]来限制查询可能对你有用。 -
@WaketZheng 我没有使用 Django 模型!!
标签: python pagination django-rest-framework