Opening a connection to an additional database specifying cursor_factory

Viewed 40

I've defined a named database in settings.py::DATABASES, called db.

I want to open a connection to that database and get a NamedTupleCursor instead of the default psycopg2 cursor.

Ny naive attempt was to do:

from psycopg2.extras import NamedTupleCursor

db = connections["db"].connection
with db.cursor(cursor_factory=NamedTupleCursor) as cursor:
    ...

But .connection is None until I explicitly connect to the database.

I can manually connect to the database, then access the underlying connection, like this:

db = connections["db"]
if not db.connection:
    db.connect()
connection = db.connection
with connection.cursor(cursor_factory=NamedTupleCursor) as cursor:
    ...

But this all feels very ad-hoc and un-Djangoesque. Also, I'm not sure whether the connection will ever be closed because I haven't used a context manager.

Is there an accepted way to get a connection to one of your DATABASES which will allow me to specify the cursor_factory?

0 Answers
Related