python - 有没有办法在单个查询中获取表行和表数据的总数
问题描述
问题是,要获取计数和表格数据,我必须在 Django 中访问数据库两次。例如:
count = queryset.count() # To get count
data = queryset.values('columns') # To get data
有没有办法在单个查询中获取数据。一种解决方案是使用 len() 函数,但不适合将更大的表加载到 RAM 中。
在mysql中,我得到了这个,但是如何通过Django ORM执行
SELECT t1.count, id FROM table1, (select count(*) as count FROM table1) as t1 limit 10;
任何帮助将不胜感激。
解决方案
我的意思len
是,如果您首先获取数据,则应该只计算内存中已经存在的内容,因此它应该比对数据库的两次查询要好。
data = queryset.values('columns') # To get data
count = len(data) # To get count from database records in memory
无论如何,对于没有来自 Django 文档的模型层的直接数据库查询:
from django.db import connection
def my_custom_sql(self):
with connection.cursor() as cursor:
cursor.execute("SELECT t1.count, id FROM table1, (select count(*) as count FROM table1) as t1 limit 10")
row = dictfetchall(cursor)
return row
推荐阅读
- java - 自定义 SQL 查询和 Spring Data JPA
- docker - 如何从 env_file 获取 docker-compose 的端口?
- javascript - 在 autotable 之前添加 div 内容
- java - 流集中的正则表达式
- json - 如何从 ionic 中的嵌套 json 响应中打印数据
- php - 如何将 html 标签添加到选项
- amazon-s3 - 如何在不耗尽资源的情况下使用 Amazon Athena 执行查询?
- reactjs - 在 Mocha 测试中使用 webpack 插件
- java - 什么是用于搜索的 Retrofit OR 运算符
- java - 无法从 swt 中的表中删除表项