首页 > 解决方案 > 如何在 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")''')

但结果sizeNone

如何执行此查询?目的是返回数据库的大小。

标签: djangopython-3.xpostgresql

解决方案


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()

推荐阅读