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.

  1. # Connect to our database.
  2. db.connect()
  3. # Create the tables.
  4. 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 will determine if your tables already exist, and conditionally create them. 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.