Using Postgresql

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

  1. psql_db = PostgresqlDatabase('my_database', user='postgres')
  2.  
  3. class BaseModel(Model):
  4. """A base model that will use our Postgresql database"""
  5. class Meta:
  6. database = psql_db
  7.  
  8. class User(BaseModel):
  9. 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 thePostgresqlExtDatabase from the playhouse.postgres_ext module:

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

Isolation level

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

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

Note

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

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

To run this every time a connection is created, subclass and implementthe _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)