Search code examples
pythonpeewee

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


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?


Solution

  • 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:

    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.