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 your data model, by defining one or more Model classes:

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

Note

Peewee will automatically infer the database table name from the name of the class. You can override the default name by specifying a table_name attribute 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 is a convention you should follow – even though the table will contain multiple people, we always name the class using the singular form.

There are lots of field types suitable for storing various types of data. Peewee handles converting between pythonic values and those used by the database, so you can use Python types in your code without having to worry.

Things get interesting when we set up relationships between models using foreign 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. class Meta:
  6. database = db # this model uses the "people.db" database

Now that we have our models, let’s connect to the database. Although it’s not necessary to open the connection explicitly, it is good practice since it will reveal any errors with your database connection immediately, as opposed to some arbitrary time later when the first query is executed. It is also good to close the connection when you are done – for instance, a web app might open a connection when it receives a request, and close the connection when it sends the 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])