Using Postgresql

To connect to a Postgresql database, we will use PostgresqlDatabase. The first parameter is always the name of the database, and after that you can specify arbitrary psycopg2 parameters.

  1. psql_db = PostgresqlDatabase('my_database', user='postgres')
  2. class BaseModel(Model):
  3. """A base model that will use our Postgresql database"""
  4. class Meta:
  5. database = psql_db
  6. class User(BaseModel):
  7. username = CharField()

The Playhouse, extensions to Peewee contains a Postgresql extension module which provides many postgres-specific features such as:

If you would like to use these awesome features, use the PostgresqlExtDatabase from the playhouse.postgres_ext module:

  1. from playhouse.postgres_ext import PostgresqlExtDatabase
  2. psql_db = PostgresqlExtDatabase('my_database', user='postgres')

Isolation level

As of Peewee 3.9.7, the isolation level can be specified as an initialization parameter, using the symbolic constants in psycopg2.extensions:

  1. from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
  2. db = PostgresqlDatabase('my_app', user='postgres', host='db-host',
  3. isolation_level=ISOLATION_LEVEL_SERIALIZABLE)

Note

In older versions, you can manually set the isolation level on the underlying psycopg2 connection. This can be done in a one-off fashion:

  1. db = PostgresqlDatabase(...)
  2. conn = db.connection() # returns current connection.
  3. from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
  4. conn.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)

To run this every time a connection is created, subclass and implement the _initialize_database() hook, which is designed for this purpose:

  1. class SerializedPostgresqlDatabase(PostgresqlDatabase):
  2. def _initialize_connection(self, conn):
  3. conn.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)