Creating model tables
In order to start using our models, its necessary to open a connection to the database and create the tables first. Peewee will run the necessary CREATE TABLE queries, additionally creating any constraints and indexes.
# Connect to our database.
db.connect()
# Create the tables.
db.create_tables([User, Tweet])
Note
Strictly speaking, it is not necessary to call connect()
but it is good practice to be explicit. That way if something goes wrong, the error occurs at the connect step, rather than some arbitrary time later.
Note
By default, Peewee includes an IF NOT EXISTS
clause when creating tables. If you want to disable this, specify safe=False
.
After you have created your tables, if you choose to modify your database schema (by adding, removing or otherwise changing the columns) you will need to either:
- Drop the table and re-create it.
- Run one or more ALTER TABLE queries. Peewee comes with a schema migration tool which can greatly simplify this. Check the schema migrations docs for details.