Model Definition

Model classes, fields and model instances all map to database concepts:

ObjectCorresponds to…
Model classDatabase table
Field instanceColumn on a table
Model instanceRow in a database table

When starting a project with peewee, it’s typically best to begin with yourdata model, by defining one or more Model classes:

  1. from peewee import *
  2.  
  3. db = SqliteDatabase('people.db')
  4.  
  5. class Person(Model):
  6. name = CharField()
  7. birthday = DateField()
  8.  
  9. class Meta:
  10. database = db # This model uses the "people.db" database.

Note

Peewee will automatically infer the database table name from the name ofthe class. You can override the default name by specifying a table_nameattribute in the inner “Meta” class (alongside the database attribute).To learn more about how Peewee generates table names,refer to the Table Names section.

Also note that we named our model Person instead of People. This isa convention you should follow – even though the table will containmultiple people, we always name the class using the singular form.

There are lots of field types suitable for storing varioustypes of data. Peewee handles converting between pythonic values those usedby the database, so you can use Python types in your code without having toworry.

Things get interesting when we set up relationships between models usingforeign key relationships. This is simple with peewee:

  1. class Pet(Model):
  2. owner = ForeignKeyField(Person, backref='pets')
  3. name = CharField()
  4. animal_type = CharField()
  5.  
  6. class Meta:
  7. database = db # this model uses the "people.db" database

Now that we have our models, let’s connect to the database. Although it’s notnecessary to open the connection explicitly, it is good practice since it willreveal any errors with your database connection immediately, as opposed to somearbitrary time later when the first query is executed. It is also good to closethe connection when you are done – for instance, a web app might open aconnection when it receives a request, and close the connection when it sendsthe response.

  1. db.connect()

We’ll begin by creating the tables in the database that will store our data.This will create the tables with the appropriate columns, indexes, sequences,and foreign key constraints:

  1. db.create_tables([Person, Pet])