Models and Fields

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

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

The following code shows the typical way you will define your database connection and model classes.

  1. from peewee import *
  2. db = SqliteDatabase('my_app.db')
  3. class BaseModel(Model):
  4. class Meta:
  5. database = db
  6. class User(BaseModel):
  7. username = CharField(unique=True)
  8. class Tweet(BaseModel):
  9. user = ForeignKeyField(User, backref='tweets')
  10. message = TextField()
  11. created_date = DateTimeField(default=datetime.datetime.now)
  12. is_published = BooleanField(default=True)
  1. Create an instance of a Database.

    1. db = SqliteDatabase('my_app.db')

    The db object will be used to manage the connections to the Sqlite database. In this example we’re using SqliteDatabase, but you could also use one of the other database engines.

  2. Create a base model class which specifies our database.

    1. class BaseModel(Model):
    2. class Meta:
    3. database = db

    It is good practice to define a base model class which establishes the database connection. This makes your code DRY as you will not have to specify the database for subsequent models.

    Model configuration is kept namespaced in a special class called Meta. This convention is borrowed from Django. Meta configuration is passed on to subclasses, so our project’s models will all subclass BaseModel. There are many different attributes you can configure using Model.Meta.

  3. Define a model class.

    1. class User(BaseModel):
    2. username = CharField(unique=True)

    Model definition uses the declarative style seen in other popular ORMs like SQLAlchemy or Django. Note that we are extending the BaseModel class so the User model will inherit the database connection.

    We have explicitly defined a single username column with a unique constraint. Because we have not specified a primary key, peewee will automatically add an auto-incrementing integer primary key field named id.

Note

If you would like to start using peewee with an existing database, you can use pwiz, a model generator to automatically generate model definitions.