在Django中,我试图在cursor.execute()
中使用dt
来获取PostgreSQL中的表,如下所示:
# "views.py"
from django.http import HttpResponse
from django.db import connection
def test(request):
cursor = connection.cursor()
cursor.execute('''dt''') # Here
row = cursor.fetchone()
print(row)
return HttpResponse("Test")
但是,我得到了以下错误:
django.db.utils.ProgrammingError:"处或附近的语法错误\">
LINE 1:\dt
因此,我将cursor.execute('''dt''')
替换为cursor.execute('''\dt''')
,如下所示:
# "views.py"
from django.http import HttpResponse
from django.db import connection
def test(request):
# ...
cursor.execute('''\dt''') # Here
# ...
return HttpResponse("Test")
但是,我仍然得到以下错误:
django.db.utils.ProgrammingError:"处或附近的语法错误\">
LINE 1:\dt
那么,如何在cursor.execute()
中使用dt
来获取PostgreSQL中的表?
您可以使用纯SQL列出表,而不需要psql。
cursor.execute('''
select *
from pg_catalog.pg_tables
where schemaname = '<your_schema_name>';
''')
不能将dt
命令用作postgresql查询。dt
是客户端psql
命令。PostgreSQL只能处理SQL命令(如SELECT
、INSERT
、ALTER
…(
但有一些方法:
- 使用参数
-E
运行psql
。这意味着回声所有 - 运行选定的反斜杠命令(如
dt
( - psql打印结果(以及为获取结果而生成的SQL查询(
- 从Django执行此查询