DEV Community

Cover image for Python Django `dbshell`
Mikołaj Buchwald
Mikołaj Buchwald

Posted on • Updated on

Python Django `dbshell`

Python Django's dbshell is a very useful tool for SQL database debugging when working on a Django application.

To run SQL shell interactively:

python dbshell
Enter fullscreen mode Exit fullscreen mode

You should see:

SQLite version 3.32.3 2020-06-18 14:16:19
Enter ".help" for usage hints.
Enter fullscreen mode Exit fullscreen mode

Useful Django sqlite commands:

Enter fullscreen mode Exit fullscreen mode

An example SQL command:

SELECT * FROM django_migrations;
Enter fullscreen mode Exit fullscreen mode

In order to see the names of the columns (the header) of the table:

.header on
.mode column
pragma table_info('django_migrations');
Enter fullscreen mode Exit fullscreen mode

Example output:

sqlite> pragma table_info('django_migrations');
cid         name        type        notnull     dflt_value  pk        
----------  ----------  ----------  ----------  ----------  ----------
0           id          integer     1                       1         
1           app         varchar(25  1                       0         
2           name        varchar(25  1                       0         
3           applied     datetime    1                       0      
Enter fullscreen mode Exit fullscreen mode

See also this StackOverflow answer.

Top comments (3)

sangeeky profile image
Santiago Pinchao

This command also works with Postgres DB ?

mikolajbuchwald profile image
Mikołaj Buchwald

Most probably yes, but there are several thing you have to have in mind:

(1) You need to have psql installed for this utility to work on the same shell/system that you are using your application on (python ...). That is why, e.g., when your application is dockerized, and you (usually) don't have postgress installed in the same container as the application, you will get the following error:

CommandError: You appear not to have the 'psql' program installed or on your path.
Enter fullscreen mode Exit fullscreen mode

(2) You have to make sure that your Posgress DB is the one that is configured in the (you can use environmental variables to switch between developemnt mode SQL Lite and Postgress DB).

And you of course have to have Postgress DB configured and running. -- I am emphasising on that because, as in my situation, when you are using dockerized application you often have DB also dockerized or you are using some external DB (i.e., on a different server).

I will test it some day when I will have Posgress running locally and configured for an application I will be working on, and I will let know in this thread whether I confirmed that it works.

StackOverflow suggests that dbshell works with Postgress:

por85 profile image

will work