首页 > 解决方案 > 有没有办法在单个查询中获取表行和表数据的总数

问题描述

问题是,要获取计数和表格数据,我必须在 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;

任何帮助将不胜感激。

标签: pythondjangodjango-orm

解决方案


我的意思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

推荐阅读