How can I force django to restart a database connection from the shell?

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))

You can use something like below

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

or

from django.db import connection
connection.connect()

Tags:

Python

Django