Search code examples
pythondjangodjango-modelsintrospectiondjango-database

Django: How do I perform database introspection with multiple databases?


I have code that works for getting models and fields from a Django database. However, it only works on the default database.

This function wants a database name, and I'd like to get the tables and fields for that database.

def browse_datasource(request, dbname):
    table_info = []
    # This is what I'd /like/ to be able to do, but it doesn't work:
    # tables = connections[dbname].introspection.table_names()
    tables = connection.introspection.table_names()
    found_models = connection.introspection.installed_models(tables)
    for model in found_models:
        tablemeta = model._meta
        columns = [field.column for field in model._meta.fields]
        table_info.append([model.__name__, columns])

How can I perform introspection on the non-default databases? Is there a correct way to get connection.introspection for a database with the name "example", for example?


Solution

  • I found the solution. The trick is getting the database connection from the connections list, then getting a cursor and passing that to introspection.table_names, like so:

    table_info = []
    conn = connections[dbname]
    cursor = conn.cursor()
    tables = conn.introspection.table_names(cursor)
    found_models = conn.introspection.installed_models(tables)
    for model in found_models:
        tablemeta = model._meta