Creating model tables

In order to start using our models, its necessary to open a connection to thedatabase and create the tables first. Peewee will run the necessary CREATETABLE queries, additionally creating any constraints and indexes.

  1. # Connect to our database.
  2. db.connect()
  3.  
  4. # Create the tables.
  5. 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 timelater.

Note

By default, Peewee includes an IF NOT EXISTS clause when creatingtables. If you want to disable this, specify safe=False.

After you have created your tables, if you choose to modify your databaseschema (by adding, removing or otherwise changing the columns) you will need toeither:

  • Drop the table and re-create it.
  • Run one or more ALTER TABLE queries. Peewee comes with a schema migrationtool which can greatly simplify this. Check the schema migrationsdocs for details.