title: How can I force django to restart a database connection from the shell?
body: <p>I have a django project on a Digital Ocean server. From my local machine, I connect to the database through ssh:</p>
  
  <pre><code>ssh -L 63333:localhost:5432 me@my.server
  </code></pre>
  
  <p>And change my local settings.py as:</p>
  
  <pre><code>DATABASES = {
      'default': {
          'ENGINE': 'django.db.backends.postgresql_psycopg2',
          'NAME': '',
          'USER': '',
          'PASSWORD': '',
          'HOST': 'localhost',
          'PORT': 63333
      }
  }
  </code></pre>
  
  <p>And on a Jupyter QtConsole on my local machine, I follow these steps for setup:</p>
  
  <pre><code>import os
  import django
  os.chdir('/path/to/my/project')
  os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings'
  django.setup()
  </code></pre>
  
  <p>It all works fine until my ssh connection is broken by some reason. First I get this error (on a line that queries the database, say, <code>my_model.objects.first()</code>):</p>
  
  <pre><code>DatabaseErrorTraceback (most recent call last)
  /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args)
       84             else:
  ---&gt; 85                 return self.cursor.execute(sql, params)
       86 
  
  DatabaseError: server closed the connection unexpectedly
      This probably means the server terminated abnormally
      before or while processing the request.
  </code></pre>
  
  <p>When I reconnect through ssh, I keep getting the following error:</p>
  
  <pre><code>InterfaceErrorTraceback (most recent call last)
  /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py in _cursor(self, name)
      233         with self.wrap_database_errors:
  --&gt; 234             return self._prepare_cursor(self.create_cursor(name))
      235 
  
  /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/postgresql/base.py in create_cursor(self, name)
      211         else:
  --&gt; 212             cursor = self.connection.cursor()
      213         cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None
  
  InterfaceError: connection already closed
  </code></pre>
  
  <p>The error only goes away if I restart the IPython kernel. I tried executing the same steps for the setup. I also tried <code>from importlib import reload; reload(django)</code> and then doing the setup again but it gives the same error no matter what.</p>
  
  <p>Sometimes this happens while I have variables that I don't want to lose in the memory so I want to avoid restarting the kernel. Is there a way to recreate the database connection without it? I am using Python 3.6 and django 2.0.0.</p>