In Django, I'm trying to use \dt
in cursor.execute()
to get the tables in PostgreSQL as shown below:
# "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")
But, I got the error below:
django.db.utils.ProgrammingError: syntax error at or near "\"
LINE 1: \dt
So, I replaced cursor.execute('''\dt''')
with cursor.execute('''\\dt''')
as shown below:
# "views.py"
from django.http import HttpResponse
from django.db import connection
def test(request):
# ...
cursor.execute('''\\dt''') # Here
# ...
return HttpResponse("Test")
But, I still got the error below:
django.db.utils.ProgrammingError: syntax error at or near "\"
LINE 1: \dt
So, how do I use \dt
in cursor.execute()
to get the tables in PostgreSQL?
CodePudding user response:
You cannot to use \dt
command as postgresql query. \dt
is client side psql
command. PostgreSQL can process just SQL commands (like SELECT
,INSERT
, ALTER
, ...).
But there is some way:
- run
psql
with parameter-E
. That means echo all, - run selected backslash command (like
\dt
) - psql prints the result (and the SQL query generated for getting the result)
- execute from Django this query
CodePudding user response:
You can list the tables using plain SQL, without the need of psql.
cursor.execute('''
select *
from pg_catalog.pg_tables
where schemaname = '<your_schema_name>';
''')