django - 如何在 Django 中正确执行查询?
问题描述
我需要执行SELECT pg_database_size ('mydatabase')
查询,如何在 Django 中使用 Postgres DBMS 执行此操作?
我已经尝试过执行以下操作
from django.db import connection
cursor = connection.cursor()
size = cursor.execute('''SELECT pg_database_size("mydatabase")''')
但结果size
是None
。
如何执行此查询?目的是返回数据库的大小。
解决方案
That's almost right, but note that while cursor.execute()
will execute the SQL, cursor.fetchall()
is needed to return the result. More info in the docs.
Try doing the following:
from django.db import connection
with connection.cursor() as cursor:
cursor.execute('SELECT pg_database_size("mydatabase")')
size = cursor.fetchall()
推荐阅读
- python - 如何使用pandas从某个句子的txt文件中加载jupyter表
- javascript - 去抖动功能不起作用 - REACT 功能组件
- javascript - 具有多个可选参数的函数的控制台输出
- azure-ad-b2c - 带有身份验证/注销的 ADB2C 在 Blazor 中不起作用
- python - 如何使用字符串引用列表中对象的属性?
- reactjs - Reactjs React.memo 不记忆 const 函数
- python - 为什么 input( ) 在遇到换行符后不停止?
- c++ - c ++类/结构中的功能依赖属性
- python - ModuleNotFoundError:没有名为“flask”的模块,我做错了什么?
- list - Dart - 在列表中查找重复值