skip to Main Content

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?

2

Answers


  1. 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:

    1. run psql with parameter -E. That means echo all,
    2. run selected backslash command (like dt)
    3. psql prints the result (and the SQL query generated for getting the result)
    4. execute from Django this query
    Login or Signup to reply.
  2. 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>';
    ''')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search