Django:如何对多个数据库执行数据库自省?
Django: How do I perform database introspection with multiple databases?
我有代码可以从 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 的正确方法?
我找到了解决方案。诀窍是从连接列表中获取数据库连接,然后获取游标并将其传递给 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
我有代码可以从 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 的正确方法?
我找到了解决方案。诀窍是从连接列表中获取数据库连接,然后获取游标并将其传递给 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