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.
- psql_db = PostgresqlDatabase('my_database', user='postgres')
- class BaseModel(Model):
- """A base model that will use our Postgresql database"""
- class Meta:
- database = psql_db
- class User(BaseModel):
- username = CharField()
The Playhouse, extensions to Peewee contains a Postgresql extension module which provides many postgres-specific features such as:
- Arrays
- HStore
- JSON
- Server-side cursors
- And more!
If you would like to use these awesome features, use thePostgresqlExtDatabase
from the playhouse.postgres_ext
module:
- from playhouse.postgres_ext import PostgresqlExtDatabase
- 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
:
- from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
- db = PostgresqlDatabase('my_app', user='postgres', host='db-host',
- 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:
- db = PostgresqlDatabase(...)
- conn = db.connection() # returns current connection.
- from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
- 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:
- class SerializedPostgresqlDatabase(PostgresqlDatabase):
- def _initialize_connection(self, conn):
- conn.set_isolation_level(ISOLATION_LEVEL_SERIALIZABLE)