我能以某种方式查询 peewee / postgres 中的所有现有表吗?

Can I somehow query all the existing tables in peewee / postgres?

我正在为使用 Peewee 的程序编写基本图形用户界面。在 gui 中,我想显示我数据库中存在的所有表。

有没有办法获取所有现有表的名称,比如在列表中?

要获取架构中的表列表,请确保已建立连接和游标并尝试以下操作:

cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_schema='public'")
myables = cursor.fetchall()
mytables = [x[0] for x in mytables]

希望对您有所帮助。

Peewee 能够内省 Postgres、MySQL 和 SQLite 以获取以下类型的模式信息:

  • Table 名字
  • 列(名称,数据类型,空?,主键?,table)
  • 主键(列)
  • 外键(列,dest table,dest 列,table)
  • 索引(名称,sql*,列,唯一?,table)

您可以在 Database class 上使用以下方法获取此元数据:

所以,与其使用游标并自己编写一些 SQL,不如这样做:

db = PostgresqlDatabase('my_db')
tables = db.get_tables()

更疯狂的是,查看 reflection 模块,它实际上可以从现有数据库模式生成 Peewee 模型 classes。