添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am writing a basic gui for a program which uses Peewee. In the gui, I would like to show all the tables which exist in my database.

Is there any way to get the names of all existing tables, lets say in a list?

If you already have your connection established, run SELECT table_name FROM information_schema.tables WHERE table_schema='public' to get the table names in your schema. That should return a list of 1-element tuples. Abdou Jul 27, 2016 at 17:55

Peewee has the ability to introspect Postgres, MySQL and SQLite for the following types of schema information:

  • Table names
  • Columns (name, data type, null?, primary key?, table)
  • Primary keys (column(s))
  • Foreign keys (column, dest table, dest column, table)
  • Indexes (name, sql*, columns, unique?, table)
  • You can get this metadata using the following methods on the Database class:

  • Database.get_tables()
  • Database.get_columns()
  • Database.get_indexes()
  • Database.get_primary_keys()
  • Database.get_foreign_keys()
  • So, instead of using a cursor and writing some SQL yourself, just do:

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

    For even more craziness, check out the reflection module, which can actually generate Peewee model classes from an existing database schema.

    To get a list of the tables in your schema, make sure that you have established your connection and cursor and try the following:

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

    I hope this helps.

    This is really not the best way to do this with Peewee. Much better would be to use the "database.get_tables()" function. – coleifer Aug 2, 2016 at 8:07

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.