Django: find ghost tables without associated models - Adam Johnson by Adam Johnson

Heavy refactoring of models can leave a Django project with “ghost tables”, which were created for a model that was removed without any trace in the migration history. Thankfully, by using some Django internals, you can find such tables.

In [1]: from django.db import connection
 
In [2]: table_names = set(connection.introspection.table_names())
 
In [3]: django_table_names = set(connection.introspection.django_table_names())
 
In [4]: table_names - django_table_names - {"django_migrations"}
Out[4]:
{'sweetshop_humbug',
'sweetshop_jellybean',
'sweetshop_marshmallow'}