Database "is being accessed by other users" error when using ThreadPoolExecutor with Django Database "is being accessed by other users" error when using ThreadPoolExecutor with Django multithreading multithreading

Database "is being accessed by other users" error when using ThreadPoolExecutor with Django


Make sure you are calling connection.close() in your code when working with threads. This solved the issue for me, where other proposed solutions (decorator for the test methods, changing db settings, DB functions like shown by Nick above, restarting postgres) did not. Useful example


This looks like more Django's issue than Postgres' -- see for example this ticket: https://code.djangoproject.com/ticket/22420

From what you provided, I see that Django didn't close all connections to test database before making attempt to drop it. In this case, Postges tries to protect other sessions from data losses, so it cannot drop/rename the database before they all disconnect.

If you want, you can drop the test database manually, using pg_terminate_backend(..) function and pg_stat_activity view you already used:

select pg_terminate_backend(pid) from pg_stat_activity where  datname = 'DATABASE_NAME';drop database DATABASE_NAME;

If, by some reason, somebody is very quick and manages to connect between theese two commands, drop database will fail again. In such case, you can repeat it, but before that revoke rights to connect to this database from public -- this will prevent connections to it:

revoke connect on database DATABASE_NAME from public;

...and then repeat operations described above.


I got similar problem and solved it by using django.test.testcases.TransactionTestCase as superclass for my test class