Django:如何使用多个数据库执行数据库内省?

时间:2016-02-09 18:36:11

标签: python django django-models introspection django-database

我的代码适用于从Django数据库中获取模型和字段。但是,它仅适用于默认数据库。

此函数需要数据库名称,我想获取该数据库的表和字段。

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])

如何在非默认数据库上执行内省?例如,是否有正确的方法来获取名为“example”的数据库的connection.introspection?

1 个答案:

答案 0 :(得分:4)

我找到了解决方案。诀窍是从连接列表获取数据库连接,然后获取游标并将其传递给introspection.table_names,如下所示:

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