How can I access the low level psycopg2 connection in Django?
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
.
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)