【问题标题】:Is there any way to get total count of table row and table data in single Query有没有办法在单个查询中获取表行和表数据的总数
【发布时间】:2019-03-09 09:45:21
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

标签: python django django-orm


【解决方案1】:

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

【讨论】:

  • 是的,@stree len() 解决了我的问题,但它会将所有数据库记录加载到内存中,这对于更大的表来说是个问题。
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 2014-02-21
相关资源
最近更新 更多