Skip to content

Instantly share code, notes, and snippets.

@rctay
Created August 16, 2010 15:18
Show Gist options
  • Save rctay/527113 to your computer and use it in GitHub Desktop.
Save rctay/527113 to your computer and use it in GitHub Desktop.
[django] check if db table exists
"""
Came up with this for satchmo's downloadable product migration, 0001_split.
"""
def db_table_exists(table, cursor=None):
try:
if not cursor:
from django.db import connection
cursor = connection.cursor()
if not cursor:
raise Exception
table_names = connection.introspection.get_table_list(cursor)
except:
raise Exception("unable to determine if the table '%s' exists" % table)
else:
return table in table_names
@vdboor
Copy link

vdboor commented May 31, 2012

FYI, In newer Django versions (at least 1.4) you can also do:

def db_table_exists(table_name):
    return table_name in connection.introspection.table_names()

@rctay
Copy link
Author

rctay commented May 31, 2012

Thanks for the tip! 😁

@vdboor
Copy link

vdboor commented May 31, 2012

You're welcome. :-) Great to have such feedback!

@zvictor
Copy link

zvictor commented Aug 16, 2012

Very helpful, thanks!

@kevinanew
Copy link

connection.introspection.table_names() is also available in django 1.3

@BertrandBordage
Copy link

👍

@CurrieBen
Copy link

CurrieBen commented Nov 30, 2018

6 years later, this is is still helping people out! Thanks a lot

@Flynnon
Copy link

Flynnon commented Jun 10, 2019

It's helpful~ thanks.

@xor0x
Copy link

xor0x commented Oct 31, 2019

It helps thank you!!!!

@hbd
Copy link

hbd commented Apr 21, 2021

Use of connection has been deprecated. This appears to be the most up to date version of this check:

from django.db import connections

def table_exists(table_name: str, connection_name: str) -> bool:
    return table_name in connections[connection_name].introspection.table_names()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment