[Solved]-How can I access the low level psycopg2 connection in Django?

13👍

You can see from the source that from django.db import connection returns a DatabaseWrapper for the default DB. In the psycopg2 backend you’ll see that the DatabaseWrapper accesses the low level connection via connection.cursor().connection.

2👍

Those answers are good but not copypastable and with outdated docs so let me fix that.
As of version 3 you use the raw connection like that

from django.db import connection

stmt = "SELECT * FROM foo"

with connection.cursor() as cursor:
    cursor.execute(stmt)

0👍

If you are using django 1.2+, you should probably change that to:

from django.db import connections['default']

or something equivalent.

👤lprsd

Leave a comment