[Solved]-Closing db connection with django's persistent connection in a multi-threaded script


I ran into the same issue just now…

Solved it by calling the following code when my thread exits:

from django.db import close_old_connections


I just upgraded and had this come up and close_old_connections in the main process before launching the sub processes does not work like the old close_connections did to give each process their own connection. But if you looked at what close_connections use to do you can recreate it docs.

So I do this in my main process before creating my sub processes.

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

And it works great. The new close_old_connections will only close the connection if it has expired or has gone away.

Leave a comment