[Django]-How can I force django to restart a database connection from the shell?

79👍

You can use something like below

from django.db import connections
conn = connections['default']
conn.connect()

or

from django.db import connection
connection.connect()

8👍

from django.db import connections, connection
for conn in connections.all():
    conn.close_if_unusable_or_obsolete()

then call connection.cursor will get a fresh connection,
django source code:

def _cursor(self, name=None):
    self.ensure_connection()
    with self.wrap_database_errors:
        return self._prepare_cursor(self.create_cursor(name))
👤Icy

Leave a comment