SQLAlchemy - 获取表列表 [英] SQLAlchemy - Getting a list of tables

查看:49
本文介绍了SQLAlchemy - 获取表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档中找不到任何关于此的信息,但是如何获取在 SQLAlchemy 中创建的表的列表?

我使用类方法来创建表.

解决方案

所有的表都收集在 SQLAlchemy MetaData 对象的 tables 属性中.要获取这些表的名称列表:

<预><代码>>>>元数据.tables.keys()['帖子'、'评论'、'用户']

如果您使用的是声明性扩展,那么您可能不会自己管理元数据.幸运的是,元数据仍然存在于基类中,

<预><代码>>>>Base = sqlalchemy.ext.declarative.declarative_base()>>>基础元数据元数据(无)

如果您想弄清楚数据库中存在哪些表,即使是那些您甚至还没有告诉 SQLAlchemy 的表,那么您可以使用表反射.然后 SQLAlchemy 将检查数据库并使用所有缺失的表更新元数据.

<预><代码>>>>metadata.reflect(引擎)

对于 Postgres,如果您有多个模式,则需要遍历引擎中的所有模式:

from sqlalchemy import inspect检查员 = 检查(引擎)schemas = inspector.get_schema_names()对于模式中的模式:打印(架构:%s"%架构)对于 inspector.get_table_names(schema=schema) 中的 table_name:对于 inspector.get_columns(table_name, schema=schema) 中的列:打印(列:%s"%列)

I couldn't find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy?

I used the class method to create the tables.

解决方案

All of the tables are collected in the tables attribute of the SQLAlchemy MetaData object. To get a list of the names of those tables:

>>> metadata.tables.keys()
['posts', 'comments', 'users']

If you're using the declarative extension, then you probably aren't managing the metadata yourself. Fortunately, the metadata is still present on the baseclass,

>>> Base = sqlalchemy.ext.declarative.declarative_base()
>>> Base.metadata
MetaData(None)

If you are trying to figure out what tables are present in your database, even among the ones you haven't even told SQLAlchemy about yet, then you can use table reflection. SQLAlchemy will then inspect the database and update the metadata with all of the missing tables.

>>> metadata.reflect(engine)

For Postgres, if you have multiple schemas, you'll need to loop thru all the schemas in the engine:

from sqlalchemy import inspect
inspector = inspect(engine)
schemas = inspector.get_schema_names()

for schema in schemas:
    print("schema: %s" % schema)
    for table_name in inspector.get_table_names(schema=schema):
        for column in inspector.get_columns(table_name, schema=schema):
            print("Column: %s" % column)

这篇关于SQLAlchemy - 获取表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆