Attention

Peewee needs your help! Do you have suggestions on how the documentation could be improved? If so, please leave a comment on this GitHub issue:

https://github.com/coleifer/peewee/issues/1640

API Documentation

This document specifies Peewee’s APIs.

Database

class Database(database[, thread_safe=True[, autorollback=False[, field_types=None[, operations=None[, \*kwargs*]]]]])

Parameters:
  • database (str) – Database name or filename for SQLite (or None to defer initialization, in which case you must call Database.init(), specifying the database name).
  • thread_safe (bool) – Whether to store connection state in a thread-local.
  • autorollback (bool) – Automatically rollback queries that fail when not in an explicit transaction.
  • field_types (dict) – A mapping of additional field types to support.
  • operations (dict) – A mapping of additional operations to support.
  • kwargs – Arbitrary keyword arguments that will be passed to the database driver when a connection is created, for example password, host, etc.

The Database is responsible for:

  • Executing queries
  • Managing connections
  • Transactions
  • Introspection

Note

The database can be instantiated with None as the database name if the database is not known until run-time. In this way you can create a database instance and then configure it elsewhere when the settings are known. This is called deferred* initialization.

Examples:

  1. # Sqlite database using WAL-mode and 32MB page-cache.
  2. db = SqliteDatabase('app.db', pragmas={
  3. 'journal_mode': 'wal',
  4. 'cache_size': -32 * 1000})
  5. # Postgresql database on remote host.
  6. db = PostgresqlDatabase('my_app', user='postgres', host='10.1.0.3',
  7. password='secret')

Deferred initialization example:

  1. db = PostgresqlDatabase(None)
  2. class BaseModel(Model):
  3. class Meta:
  4. database = db
  5. # Read database connection info from env, for example:
  6. db_name = os.environ['DATABASE']
  7. db_host = os.environ['PGHOST']
  8. # Initialize database.
  9. db.init(db_name, host=db_host, user='postgres')
  • param = '?'

    String used as parameter placeholder in SQL queries.

  • quote = '"'

    Type of quotation-mark to use to denote entities such as tables or columns.

  • init(database[, \*kwargs*])

    Parameters:
    • database (str) – Database name or filename for SQLite.
    • kwargs – Arbitrary keyword arguments that will be passed to the database driver when a connection is created, for example password, host, etc.

    Initialize a deferred database. See Run-time database configuration for more info.

  • __enter__()

    The Database instance can be used as a context-manager, in which case a connection will be held open for the duration of the wrapped block.

    Additionally, any SQL executed within the wrapped block will be executed in a transaction.

  • connection_context()

    Create a context-manager that will hold open a connection for the duration of the wrapped block.

    Example:

    1. def on_app_startup():
    2. # When app starts up, create the database tables, being sure
    3. # the connection is closed upon completion.
    4. with database.connection_context():
    5. database.create_tables(APP_MODELS)
  • connect([reuse_if_open=False])

    Parameters:reuse_if_open (bool) – Do not raise an exception if a connection is already opened.
    Returns:whether a new connection was opened.
    Return type:bool
    Raises:OperationalError if connection already open and reuse_if_open is not set to True.

    Open a connection to the database.

  • close()

    Returns:Whether a connection was closed. If the database was already closed, this returns False.
    Return type:bool

    Close the connection to the database.

  • is_closed()

    Returns:return True if database is closed, False if open.
    Return type:bool
  • connection()

    Return the open connection. If a connection is not open, one will be opened. The connection will be whatever the underlying database-driver uses to encapsulate a database connection.

  • cursor([commit=None])

    Parameters:commit – For internal use.

    Return a cursor object on the current connection. If a connection is not open, one will be opened. The cursor will be whatever the underlying database-driver uses to encapsulate a database cursor.

  • execute_sql(sql[, params=None[, commit=SENTINEL]])

    Parameters:
    • sql (str) – SQL string to execute.
    • params (tuple) – Parameters for query.
    • commit – Boolean flag to override the default commit logic.
    Returns:

    cursor object.

    Execute a SQL query and return a cursor over the results.

  • execute(query[, commit=SENTINEL[, \*context_options*]])

    Parameters:
    • query – A Query instance.
    • commit – Boolean flag to override the default commit logic.
    • context_options – Arbitrary options to pass to the SQL generator.
    Returns:

    cursor object.

    Execute a SQL query by compiling a Query instance and executing the resulting SQL.

  • last_insert_id(cursor[, query_type=None])

    Parameters:cursor – cursor object.
    Returns:primary key of last-inserted row.
  • rows_affected(cursor)

    Parameters:cursor – cursor object.
    Returns:number of rows modified by query.
  • in_transaction()

    Returns:whether or not a transaction is currently open.
    Return type:bool
  • atomic()

    Create a context-manager which runs any queries in the wrapped block in a transaction (or save-point if blocks are nested).

    Calls to atomic() can be nested.

    atomic() can also be used as a decorator.

    Example code:

    1. with db.atomic() as txn:
    2. perform_operation()
    3. with db.atomic() as nested_txn:
    4. perform_another_operation()

    Transactions and save-points can be explicitly committed or rolled-back within the wrapped block. If this occurs, a new transaction or savepoint is begun after the commit/rollback.

    Example:

    1. with db.atomic() as txn:
    2. User.create(username='mickey')
    3. txn.commit() # Changes are saved and a new transaction begins.
    4. User.create(username='huey')
    5. txn.rollback() # "huey" will not be saved.
    6. User.create(username='zaizee')
    7. # Print the usernames of all users.
    8. print [u.username for u in User.select()]
    9. # Prints ["mickey", "zaizee"]
  • manual_commit()

    Create a context-manager which disables all transaction management for the duration of the wrapped block.

    Example:

    1. with db.manual_commit():
    2. db.begin() # Begin transaction explicitly.
    3. try:
    4. user.delete_instance(recursive=True)
    5. except:
    6. db.rollback() # Rollback -- an error occurred.
    7. raise
    8. else:
    9. try:
    10. db.commit() # Attempt to commit changes.
    11. except:
    12. db.rollback() # Error committing, rollback.
    13. raise

    The above code is equivalent to the following:

    1. with db.atomic():
    2. user.delete_instance(recursive=True)
  • transaction()

    Create a context-manager that runs all queries in the wrapped block in a transaction.

    Warning

    Calls to transaction cannot be nested. Only the top-most call will take effect. Rolling-back or committing a nested transaction context-manager has undefined behavior.

  • savepoint()

    Create a context-manager that runs all queries in the wrapped block in a savepoint. Savepoints can be nested arbitrarily.

    Warning

    Calls to savepoint must occur inside of a transaction.

  • begin()

    Begin a transaction when using manual-commit mode.

    Note

    This method should only be used in conjunction with the manual_commit() context manager.

  • commit()

    Manually commit the currently-active transaction.

    Note

    This method should only be used in conjunction with the manual_commit() context manager.

  • rollback()

    Manually roll-back the currently-active transaction.

    Note

    This method should only be used in conjunction with the manual_commit() context manager.

  • batch_commit(it, n)

    Parameters:
    • it (iterable) – an iterable whose items will be yielded.
    • n (int) – commit every n items.
    Returns:

    an equivalent iterable to the one provided, with the addition that groups of n items will be yielded in a transaction.

    The purpose of this method is to simplify batching large operations, such as inserts, updates, etc. You pass in an iterable and the number of items-per-batch, and the items will be returned by an equivalent iterator that wraps each batch in a transaction.

    Example:

    1. # Some list or iterable containing data to insert.
    2. row_data = [{'username': 'u1'}, {'username': 'u2'}, ...]
    3. # Insert all data, committing every 100 rows. If, for example,
    4. # there are 789 items in the list, then there will be a total of
    5. # 8 transactions (7x100 and 1x89).
    6. for row in db.batch_commit(row_data, 100):
    7. User.create(**row)

    An alternative that may be more efficient is to batch the data into a multi-value INSERT statement (for example, using Model.insert_many()):

    1. with db.atomic():
    2. for idx in range(0, len(row_data), 100):
    3. # Insert 100 rows at a time.
    4. rows = row_data[idx:idx + 100]
    5. User.insert_many(rows).execute()
  • table_exists(table[, schema=None])

    Parameters:
    • table (str) – Table name.
    • schema (str) – Schema name (optional).
    Returns:

    bool indicating whether table exists.

  • get_tables([schema=None])

    Parameters:schema (str) – Schema name (optional).
    Returns:a list of table names in the database.
  • get_indexes(table[, schema=None])

    Parameters:
    • table (str) – Table name.
    • schema (str) – Schema name (optional).

    Return a list of IndexMetadata tuples.

    Example:

    1. print(db.get_indexes('entry'))
    2. [IndexMetadata(
    3. name='entry_public_list',
    4. sql='CREATE INDEX "entry_public_list" ...',
    5. columns=['timestamp'],
    6. unique=False,
    7. table='entry'),
    8. IndexMetadata(
    9. name='entry_slug',
    10. sql='CREATE UNIQUE INDEX "entry_slug" ON "entry" ("slug")',
    11. columns=['slug'],
    12. unique=True,
    13. table='entry')]
  • get_columns(table[, schema=None])

    Parameters:
    • table (str) – Table name.
    • schema (str) – Schema name (optional).

    Return a list of ColumnMetadata tuples.

    Example:

    1. print(db.get_columns('entry'))
    2. [ColumnMetadata(
    3. name='id',
    4. data_type='INTEGER',
    5. null=False,
    6. primary_key=True,
    7. table='entry'),
    8. ColumnMetadata(
    9. name='title',
    10. data_type='TEXT',
    11. null=False,
    12. primary_key=False,
    13. table='entry'),
    14. ...]
  • get_primary_keys(table[, schema=None])

    Parameters:
    • table (str) – Table name.
    • schema (str) – Schema name (optional).

    Return a list of column names that comprise the primary key.

    Example:

    1. print(db.get_primary_keys('entry'))
    2. ['id']
  • get_foreign_keys(table[, schema=None])

    Parameters:
    • table (str) – Table name.
    • schema (str) – Schema name (optional).

    Return a list of ForeignKeyMetadata tuples for keys present on the table.

    Example:

    1. print(db.get_foreign_keys('entrytag'))
    2. [ForeignKeyMetadata(
    3. column='entry_id',
    4. dest_table='entry',
    5. dest_column='id',
    6. table='entrytag'),
    7. ...]
  • get_views([schema=None])

    Parameters:schema (str) – Schema name (optional).

    Return a list of ViewMetadata tuples for VIEWs present in the database.

    Example:

    1. print(db.get_views())
    2. [ViewMetadata(
    3. name='entries_public',
    4. sql='CREATE VIEW entries_public AS SELECT ... '),
    5. ...]
  • sequence_exists(seq)

    Parameters:seq (str) – Name of sequence.
    Returns:Whether sequence exists.
    Return type:bool
  • create_tables(models[, \*options*])

    Parameters:

    Create tables, indexes and associated metadata for the given list of models.

    Dependencies are resolved so that tables are created in the appropriate order.

  • drop_tables(models[, \*options*])

    Parameters:

    Drop tables, indexes and associated metadata for the given list of models.

    Dependencies are resolved so that tables are dropped in the appropriate order.

  • bind(models[, bind_refs=True[, bind_backrefs=True]])

    Parameters:
    • models (list) – One or more Model classes to bind.
    • bind_refs (bool) – Bind related models.
    • bind_backrefs (bool) – Bind back-reference related models.

    Bind the given list of models, and specified relations, to the database.

  • bind_ctx(models[, bind_refs=True[, bind_backrefs=True]])

    Parameters:
    • models (list) – List of models to bind to the database.
    • bind_refs (bool) – Bind models that are referenced using foreign-keys.
    • bind_backrefs (bool) – Bind models that reference the given model with a foreign-key.

    Create a context-manager that binds (associates) the given models with the current database for the duration of the wrapped block.

    Example:

    ``` MODELS = (User, Account, Note)

    Bind the given models to the db for the duration of wrapped block.

    def use_test_database(fn):

    1. @wraps(fn)
    2. def inner(self):
    3. with test_db.bind_ctx(MODELS):
    4. test_db.create_tables(MODELS)
    5. try:
    6. fn(self)
    7. finally:
    8. test_db.drop_tables(MODELS)
    9. return inner
  1. class TestSomething(TestCase):
  2. @use_test_database
  3. def test_something(self):
  4. # ... models are bound to test database ...
  5. pass
  6. ```

class SqliteDatabase(database[, pragmas=None[, timeout=5[, \*kwargs*]]])

Parameters:
  • pragmas – Either a dictionary or a list of 2-tuples containing pragma key and value to set every time a connection is opened.
  • timeout – Set the busy-timeout on the SQLite driver (in seconds).

Sqlite database implementation. SqliteDatabase that provides some advanced features only offered by Sqlite.

  • Register custom aggregates, collations and functions
  • Load C extensions
  • Advanced transactions (specify lock type)
  • For even more features, see SqliteExtDatabase.

Example of initializing a database and configuring some PRAGMAs:

  1. db = SqliteDatabase('my_app.db', pragmas=(
  2. ('cache_size', -16000), # 16MB
  3. ('journal_mode', 'wal'), # Use write-ahead-log journal mode.
  4. ))
  5. # Alternatively, pragmas can be specified using a dictionary.
  6. db = SqliteDatabase('my_app.db', pragmas={'journal_mode': 'wal'})
  • pragma(key[, value=SENTINEL[, permanent=False]])

    Parameters:
    • key – Setting name.
    • value – New value for the setting (optional).
    • permanent – Apply this pragma whenever a connection is opened.

    Execute a PRAGMA query once on the active connection. If a value is not specified, then the current value will be returned.

    If permanent is specified, then the PRAGMA query will also be executed whenever a new connection is opened, ensuring it is always in-effect.

    Note

    By default this only affects the current connection. If the PRAGMA being executed is not persistent, then you must specify permanent=True to ensure the pragma is set on subsequent connections.

  • cache_size

    Get or set the cache_size pragma for the current connection.

  • foreign_keys

    Get or set the foreign_keys pragma for the current connection.

  • journal_mode

    Get or set the journal_mode pragma.

  • journal_size_limit

    Get or set the journal_size_limit pragma.

  • mmap_size

    Get or set the mmap_size pragma for the current connection.

  • page_size

    Get or set the page_size pragma.

  • read_uncommitted

    Get or set the read_uncommitted pragma for the current connection.

  • synchronous

    Get or set the synchronous pragma for the current connection.

  • wal_autocheckpoint

    Get or set the wal_autocheckpoint pragma for the current connection.

  • timeout

    Get or set the busy timeout (seconds).

  • register_aggregate(klass[, name=None[, num_params=-1]])

    Parameters:
    • klass – Class implementing aggregate API.
    • name (str) – Aggregate function name (defaults to name of class).
    • num_params (int) – Number of parameters the aggregate accepts, or -1 for any number.

    Register a user-defined aggregate function.

    The function will be registered each time a new connection is opened. Additionally, if a connection is already open, the aggregate will be registered with the open connection.

  • aggregate([name=None[, num_params=-1]])

    Parameters:
    • name (str) – Name of the aggregate (defaults to class name).
    • num_params (int) – Number of parameters the aggregate accepts, or -1 for any number.

    Class decorator to register a user-defined aggregate function.

    Example:

    ``` @db.aggregate(‘md5’) class MD5(object):

    1. def initialize(self):
    2. self.md5 = hashlib.md5()
    3. def step(self, value):
    4. self.md5.update(value)
    5. def finalize(self):
    6. return self.md5.hexdigest()
  1. @db.aggregate()
  2. class Product(object):
  3. '''Like SUM() except calculates cumulative product.'''
  4. def __init__(self):
  5. self.product = 1
  6. def step(self, value):
  7. self.product *= value
  8. def finalize(self):
  9. return self.product
  10. ```
  • register_collation(fn[, name=None])

    Parameters:
    • fn – The collation function.
    • name (str) – Name of collation (defaults to function name)

    Register a user-defined collation. The collation will be registered each time a new connection is opened. Additionally, if a connection is already open, the collation will be registered with the open connection.

  • collation([name=None])

    Parameters:name (str) – Name of collation (defaults to function name)

    Decorator to register a user-defined collation.

    Example:

    1. @db.collation('reverse')
    2. def collate_reverse(s1, s2):
    3. return -cmp(s1, s2)
    4. # Usage:
    5. Book.select().order_by(collate_reverse.collation(Book.title))
    6. # Equivalent:
    7. Book.select().order_by(Book.title.asc(collation='reverse'))

    As you might have noticed, the original collate_reverse function has a special attribute called collation attached to it. This extra attribute provides a shorthand way to generate the SQL necessary to use our custom collation.

  • register_function(fn[, name=None[, num_params=-1]])

    Parameters:
    • fn – The user-defined scalar function.
    • name (str) – Name of function (defaults to function name)
    • num_params (int) – Number of arguments the function accepts, or -1 for any number.

    Register a user-defined scalar function. The function will be registered each time a new connection is opened. Additionally, if a connection is already open, the function will be registered with the open connection.

  • func([name=None[, num_params=-1]])

    Parameters:
    • name (str) – Name of the function (defaults to function name).
    • num_params (int) – Number of parameters the function accepts, or -1 for any number.

    Decorator to register a user-defined scalar function.

    Example:

    1. @db.func('title_case')
    2. def title_case(s):
    3. return s.title() if s else ''
    4. # Usage:
    5. title_case_books = Book.select(fn.title_case(Book.title))
  • register_window_function(klass[, name=None[, num_params=-1]])

    Parameters:
    • klass – Class implementing window function API.
    • name (str) – Window function name (defaults to name of class).
    • num_params (int) – Number of parameters the function accepts, or -1 for any number.

    Register a user-defined window function.

    Attention

    This feature requires SQLite >= 3.25.0 and pysqlite3 >= 0.2.0.

    The window function will be registered each time a new connection is opened. Additionally, if a connection is already open, the window function will be registered with the open connection.

  • window_function([name=None[, num_params=-1]])

    Parameters:
    • name (str) – Name of the window function (defaults to class name).
    • num_params (int) – Number of parameters the function accepts, or -1 for any number.

    Class decorator to register a user-defined window function. Window functions must define the following methods:

    • step(<params>) - receive values from a row and update state.
    • inverse(<params>) - inverse of step() for the given values.
    • value() - return the current value of the window function.
    • finalize() - return the final value of the window function.

    Example:

    1. @db.window_function('my_sum')
    2. class MySum(object):
    3. def __init__(self):
    4. self._value = 0
    5. def step(self, value):
    6. self._value += value
    7. def inverse(self, value):
    8. self._value -= value
    9. def value(self):
    10. return self._value
    11. def finalize(self):
    12. return self._value
  • table_function([name=None])

    Class-decorator for registering a TableFunction. Table functions are user-defined functions that, rather than returning a single, scalar value, can return any number of rows of tabular data.

    Example:

    1. from playhouse.sqlite_ext import TableFunction
    2. @db.table_function('series')
    3. class Series(TableFunction):
    4. columns = ['value']
    5. params = ['start', 'stop', 'step']
    6. def initialize(self, start=0, stop=None, step=1):
    7. """
    8. Table-functions declare an initialize() method, which is
    9. called with whatever arguments the user has called the
    10. function with.
    11. """
    12. self.start = self.current = start
    13. self.stop = stop or float('Inf')
    14. self.step = step
    15. def iterate(self, idx):
    16. """
    17. Iterate is called repeatedly by the SQLite database engine
    18. until the required number of rows has been read **or** the
    19. function raises a `StopIteration` signalling no more rows
    20. are available.
    21. """
    22. if self.current > self.stop:
    23. raise StopIteration
    24. ret, self.current = self.current, self.current + self.step
    25. return (ret,)
    26. # Usage:
    27. cursor = db.execute_sql('SELECT * FROM series(?, ?, ?)', (0, 5, 2))
    28. for value, in cursor:
    29. print(value)
    30. # Prints:
    31. # 0
    32. # 2
    33. # 4
  • unregister_aggregate(name)

    Parameters:name – Name of the user-defined aggregate function.

    Unregister the user-defined aggregate function.

  • unregister_collation(name)

    Parameters:name – Name of the user-defined collation.

    Unregister the user-defined collation.

  • unregister_function(name)

    Parameters:name – Name of the user-defined scalar function.

    Unregister the user-defined scalar function.

  • unregister_table_function(name)

    Parameters:name – Name of the user-defined table function.
    Returns:True or False, depending on whether the function was removed.

    Unregister the user-defined scalar function.

  • load_extension(extension_module)

    Load the given C extension. If a connection is currently open in the calling thread, then the extension will be loaded for that connection as well as all subsequent connections.

    For example, if you’ve compiled the closure table extension and wish to use it in your application, you might write:

    1. db = SqliteExtDatabase('my_app.db')
    2. db.load_extension('closure')
  • attach(filename, name)

    Parameters:
    • filename (str) – Database to attach (or :memory: for in-memory)
    • name (str) – Schema name for attached database.
    Returns:

    boolean indicating success

    Register another database file that will be attached to every database connection. If the main database is currently connected, the new database will be attached on the open connection.

    Note

    Databases that are attached using this method will be attached every time a database connection is opened.

  • detach(name)

    Parameters:name (str) – Schema name for attached database.
    Returns:boolean indicating success

    Unregister another database file that was attached previously with a call to attach(). If the main database is currently connected, the attached database will be detached from the open connection.

  • transaction([lock_type=None])

    Parameters:lock_type (str) – Locking strategy: DEFERRED, IMMEDIATE, EXCLUSIVE.

    Create a transaction context-manager using the specified locking strategy (defaults to DEFERRED).

class PostgresqlDatabase(database[, register_unicode=True[, encoding=None]])

Postgresql database implementation.

Additional optional keyword-parameters:

Parameters:
  • register_unicode (bool) – Register unicode types.
  • encoding (str) – Database encoding.

class MySQLDatabase(database[, \*kwargs*])

MySQL database implementation.

Query-builder

class Node

Base-class for all components which make up the AST for a SQL query.

  • static copy(method)

    Decorator to use with Node methods that mutate the node’s state. This allows method-chaining, e.g.:

    1. query = MyModel.select()
    2. new_query = query.where(MyModel.field == 'value')
  • unwrap()

    API for recursively unwrapping “wrapped” nodes. Base case is to return self.

  • is_alias()

    API for determining if a node, at any point, has been explicitly aliased by the user.

class Source([alias=None])

A source of row tuples, for example a table, join, or select query. By default provides a “magic” attribute named “c” that is a factory for column/attribute lookups, for example:

  1. User = Table('users')
  2. query = (User
  3. .select(User.c.username)
  4. .where(User.c.active == True)
  5. .order_by(User.c.username))
  • alias(name)

    Returns a copy of the object with the given alias applied.

  • select(\columns*)

    Parameters:columnsColumn instances, expressions, functions, sub-queries, or anything else that you would like to select.

    Create a Select query on the table. If the table explicitly declares columns and no columns are provided, then by default all the table’s defined columns will be selected.

  • join(dest[, join_type=’INNER’[, on=None]])

    Parameters:
    • dest (Source) – Join the table with the given destination.
    • join_type (str) – Join type.
    • on – Expression to use as join predicate.
    Returns:

    a Join instance.

    Join type may be one of:

    • JOIN.INNER
    • JOIN.LEFT_OUTER
    • JOIN.RIGHT_OUTER
    • JOIN.FULL
    • JOIN.FULL_OUTER
    • JOIN.CROSS
  • left_outer_join(dest[, on=None])

    Parameters:
    • dest (Source) – Join the table with the given destination.
    • on – Expression to use as join predicate.
    Returns:

    a Join instance.

    Convenience method for calling join() using a LEFT OUTER join.

class BaseTable

Base class for table-like objects, which support JOINs via operator overloading.

  • __and__(dest)

    Perform an INNER join on dest.

  • __add__(dest)

    Perform a LEFT OUTER join on dest.

  • __sub__(dest)

    Perform a RIGHT OUTER join on dest.

  • __or__(dest)

    Perform a FULL OUTER join on dest.

  • __mul__(dest)

    Perform a CROSS join on dest.

class Table(name[, columns=None[, primary_key=None[, schema=None[, alias=None]]]])

Represents a table in the database (or a table-like object such as a view).

Parameters:
  • name (str) – Database table name
  • columns (tuple) – List of column names (optional).
  • primary_key (str) – Name of primary key column.
  • schema (str) – Schema name used to access table (if necessary).
  • alias (str) – Alias to use for table in SQL queries.

Note

If columns are specified, the magic “c” attribute will be disabled.

When columns are not explicitly defined, tables have a special attribute “c” which is a factory that provides access to table columns dynamically.

Example:

  1. User = Table('users')
  2. query = (User
  3. .select(User.c.id, User.c.username)
  4. .order_by(User.c.username))

Equivalent example when columns are specified:

  1. User = Table('users', ('id', 'username'))
  2. query = (User
  3. .select(User.id, User.username)
  4. .order_by(User.username))
  • bind([database=None])

    Parameters:databaseDatabase object.

    Bind this table to the given database (or unbind by leaving empty).

    When a table is bound to a database, queries may be executed against it without the need to specify the database in the query’s execute method.

  • bind_ctx([database=None])

    Parameters:databaseDatabase object.

    Return a context manager that will bind the table to the given database for the duration of the wrapped block.

  • select(\columns*)

    Parameters:columnsColumn instances, expressions, functions, sub-queries, or anything else that you would like to select.

    Create a Select query on the table. If the table explicitly declares columns and no columns are provided, then by default all the table’s defined columns will be selected.

    Example:

    1. User = Table('users', ('id', 'username'))
    2. # Because columns were defined on the Table, we will default to
    3. # selecting both of the User table's columns.
    4. # Evaluates to SELECT id, username FROM users
    5. query = User.select()
    6. Note = Table('notes')
    7. query = (Note
    8. .select(Note.c.content, Note.c.timestamp, User.username)
    9. .join(User, on=(Note.c.user_id == User.id))
    10. .where(Note.c.is_published == True)
    11. .order_by(Note.c.timestamp.desc()))
    12. # Using a function to select users and the number of notes they
    13. # have authored.
    14. query = (User
    15. .select(
    16. User.username,
    17. fn.COUNT(Note.c.id).alias('n_notes'))
    18. .join(
    19. Note,
    20. JOIN.LEFT_OUTER,
    21. on=(User.id == Note.c.user_id))
    22. .order_by(fn.COUNT(Note.c.id).desc()))
  • insert([insert=None[, columns=None[, \*kwargs*]]])

    Parameters:
    • insert – A dictionary mapping column to value, an iterable that yields dictionaries (i.e. list), or a Select query.
    • columns (list) – The list of columns to insert into when the data being inserted is not a dictionary.
    • kwargs – Mapping of column-name to value.

    Create a Insert query into the table.

  • replace([insert=None[, columns=None[, \*kwargs*]]])

    Parameters:
    • insert – A dictionary mapping column to value, an iterable that yields dictionaries (i.e. list), or a Select query.
    • columns (list) – The list of columns to insert into when the data being inserted is not a dictionary.
    • kwargs – Mapping of column-name to value.

    Create a Insert query into the table whose conflict resolution method is to replace.

  • update([update=None[, \*kwargs*]])

    Parameters:
    • update – A dictionary mapping column to value.
    • kwargs – Mapping of column-name to value.

    Create a Update query for the table.

  • delete()

    Create a Delete query for the table.

class Join(lhs, rhs[, join_type=JOIN.INNER[, on=None[, alias=None]]])

Represent a JOIN between to table-like objects.

Parameters:
  • lhs – Left-hand side of the join.
  • rhs – Right-hand side of the join.
  • join_type – Type of join. e.g. JOIN.INNER, JOIN.LEFT_OUTER, etc.
  • on – Expression describing the join predicate.
  • alias (str) – Alias to apply to joined data.
  • on(predicate)

    Parameters:predicate (Expression) – join predicate.

    Specify the predicate expression used for this join.

class ValuesList(values[, columns=None[, alias=None]])

Represent a values list that can be used like a table.

Parameters:
  • values – a list-of-lists containing the row data to represent.
  • columns (list) – the names to give to the columns in each row.
  • alias (str) – alias to use for values-list.

Example:

  1. data = [(1, 'first'), (2, 'second')]
  2. vl = ValuesList(data, columns=('idx', 'name'))
  3. query = (vl
  4. .select(vl.c.idx, vl.c.name)
  5. .order_by(vl.c.idx))
  6. # Yields:
  7. # SELECT t1.idx, t1.name
  8. # FROM (VALUES (1, 'first'), (2, 'second')) AS t1(idx, name)
  9. # ORDER BY t1.idx
  • columns(\names*)

    Parameters:names – names to apply to the columns of data.

    Example:

    1. vl = ValuesList([(1, 'first'), (2, 'second')])
    2. vl = vl.columns('idx', 'name').alias('v')
    3. query = vl.select(vl.c.idx, vl.c.name)
    4. # Yields:
    5. # SELECT v.idx, v.name
    6. # FROM (VALUES (1, 'first'), (2, 'second')) AS v(idx, name)

class CTE(name, query[, recursive=False[, columns=None]])

Represent a common-table-expression. For example queries, see Common Table Expressions.

Parameters:
  • name – Name for the CTE.
  • querySelect query describing CTE.
  • recursive (bool) – Whether the CTE is recursive.
  • columns (list) – Explicit list of columns produced by CTE (optional).
  • select_from(\columns*)

    Create a SELECT query that utilizes the given common table expression as the source for a new query.

    Parameters:columns – One or more columns to select from the CTE.
    Returns:Select query utilizing the common table expression
  • union_all(other)

    Used on the base-case CTE to construct the recursive term of the CTE.

    Parameters:other – recursive term, generally a Select query.
    Returns:a recursive CTE with the given recursive term.

class ColumnBase

Base-class for column-like objects, attributes or expressions.

Column-like objects can be composed using various operators and special methods.

  • &: Logical AND
  • |: Logical OR
  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • ^: Exclusive-OR
  • ==: Equality
  • !=: Inequality
  • >: Greater-than
  • <: Less-than
  • >=: Greater-than or equal
  • <=: Less-than or equal
  • <<: IN
  • >>: IS (i.e. IS NULL)
  • %: LIKE
  • **: ILIKE
  • bin_and(): Binary AND
  • bin_or(): Binary OR
  • in_(): IN
  • not_in(): NOT IN
  • regexp(): REGEXP
  • is_null(True/False): IS NULL or IS NOT NULL
  • contains(s): LIKE %s%
  • startswith(s): LIKE s%
  • endswith(s): LIKE %s
  • between(low, high): BETWEEN low AND high
  • concat(): ||

  • alias(alias)

    Parameters:alias (str) – Alias for the given column-like object.
    Returns:a Alias object.

    Indicate the alias that should be given to the specified column-like object.

  • cast(as_type)

    Parameters:as_type (str) – Type name to cast to.
    Returns:a Cast object.

    Create a CAST expression.

  • asc()

    Returns:an ascending Ordering object for the column.
  • desc()

    Returns:an descending Ordering object for the column.
  • __invert__()

    Returns:a Negated wrapper for the column.

class Column(source, name)

Parameters:
  • source (Source) – Source for column.
  • name (str) – Column name.

Column on a table or a column returned by a sub-query.

class Alias(node, alias)

Parameters:
  • node (Node) – a column-like object.
  • alias (str) – alias to assign to column.

Create a named alias for the given column-like object.

  • alias([alias=None])

    Parameters:alias (str) – new name (or None) for aliased column.

    Create a new Alias for the aliased column-like object. If the new alias is None, then the original column-like object is returned.

class Negated(node)

Represents a negated column-like object.

class Value(value[, converterNone[, unpack=True]])

Parameters:
  • value – Python object or scalar value.
  • converter – Function used to convert value into type the database understands.
  • unpack (bool) – Whether lists or tuples should be unpacked into a list of values or treated as-is.

Value to be used in a parameterized query. It is the responsibility of the caller to ensure that the value passed in can be adapted to a type the database driver understands.

AsIs(value)

Represents a Value that is treated as-is, and passed directly back to the database driver. This may be useful if you are using database extensions that accept native Python data-types and you do not wish Peewee to impose any handling of the values.

class Cast(node, cast)

Parameters:
  • node – A column-like object.
  • cast (str) – Type to cast to.

Represents a CAST(<node> AS <cast>) expression.

class Ordering(node, direction[, collation=None[, nulls=None]])

Parameters:
  • node – A column-like object.
  • direction (str) – ASC or DESC
  • collation (str) – Collation name to use for sorting.
  • nulls (str) – Sort nulls (FIRST or LAST).

Represent ordering by a column-like object.

  • collate([collation=None])

    Parameters:collation (str) – Collation name to use for sorting.

Asc(node[, collation=None[, nulls=None]])

Short-hand for instantiating an ascending Ordering object.

Desc(node[, collation=None[, nulls=None]])

Short-hand for instantiating an descending Ordering object.

class Expression(lhs, op, rhs[, flat=True])

Parameters:
  • lhs – Left-hand side.
  • op – Operation.
  • rhs – Right-hand side.
  • flat (bool) – Whether to wrap expression in parentheses.

Represent a binary expression of the form (lhs op rhs), e.g. (foo + 1).

class Entity(\path*)

Parameters:path – Components that make up the dotted-path of the entity name.

Represent a quoted entity in a query, such as a table, column, alias. The name may consist of multiple components, e.g. “a_table”.”column_name”.

  • __getattr__(self, attr)

    Factory method for creating sub-entities.

class SQL(sql[, params=None])

Parameters:
  • sql (str) – SQL query string.
  • params (tuple) – Parameters for query (optional).

Represent a parameterized SQL query or query-fragment.

Check(constraint)

Parameters:constraint (str) – Constraint SQL.

Represent a CHECK constraint.

class Function(name, arguments[, coerce=True])

Parameters:
  • name (str) – Function name.
  • arguments (tuple) – Arguments to function.
  • coerce (bool) – Whether to coerce the function result to a particular data-type when reading function return values from the cursor.

Represent an arbitrary SQL function call.

Note

Rather than instantiating this class directly, it is recommended to use the fn helper.

Example of using fn to call an arbitrary SQL function:

  1. # Query users and count of tweets authored.
  2. query = (User
  3. .select(User.username, fn.COUNT(Tweet.id).alias('ct'))
  4. .join(Tweet, JOIN.LEFT_OUTER, on=(User.id == Tweet.user_id))
  5. .group_by(User.username)
  6. .order_by(fn.COUNT(Tweet.id).desc()))
  • over([partition_by=None[, order_by=None[, start=None[, end=None[, window=None]]]]])

    Parameters:
    • partition_by (list) – List of columns to partition by.
    • order_by (list) – List of columns / expressions to order window by.
    • start – A SQL instance or a string expressing the start of the window range.
    • end – A SQL instance or a string expressing the end of the window range.
    • frame_type (str) – Window.RANGE or Window.ROWS.
    • window (Window) – A Window instance.

    Note

    For an in-depth guide to using window functions with Peewee, see the Window functions section.

    Examples:

    1. # Using a simple partition on a single column.
    2. query = (Sample
    3. .select(
    4. Sample.counter,
    5. Sample.value,
    6. fn.AVG(Sample.value).over([Sample.counter]))
    7. .order_by(Sample.counter))
    8. # Equivalent example Using a Window() instance instead.
    9. window = Window(partition_by=[Sample.counter])
    10. query = (Sample
    11. .select(
    12. Sample.counter,
    13. Sample.value,
    14. fn.AVG(Sample.value).over(window))
    15. .window(window) # Note call to ".window()"
    16. .order_by(Sample.counter))
    17. # Example using bounded window.
    18. query = (Sample
    19. .select(Sample.value,
    20. fn.SUM(Sample.value).over(
    21. partition_by=[Sample.counter],
    22. start=Window.CURRENT_ROW, # current row
    23. end=Window.following())) # unbounded following
    24. .order_by(Sample.id))
  • filter(where)

    Parameters:where – Expression for filtering aggregate.

    Add a FILTER (WHERE...) clause to an aggregate function. The where expression is evaluated to determine which rows are fed to the aggregate function. This SQL feature is supported for Postgres and SQLite.

  • coerce([coerce=True])

    Parameters:coerce (bool) – Whether to coerce function-call result.

fn()

The fn() helper is actually an instance of Function that implements a __getattr__ hook to provide a nice API for calling SQL functions.

To create a node representative of a SQL function call, use the function name as an attribute on fn and then provide the arguments as you would if calling a Python function:

  1. # List users and the number of tweets they have authored,
  2. # from highest-to-lowest:
  3. sql_count = fn.COUNT(Tweet.id)
  4. query = (User
  5. .select(User, sql_count.alias('count'))
  6. .join(Tweet, JOIN.LEFT_OUTER)
  7. .group_by(User)
  8. .order_by(sql_count.desc()))
  9. # Get the timestamp of the most recent tweet:
  10. query = Tweet.select(fn.MAX(Tweet.timestamp))
  11. max_timestamp = query.scalar() # Retrieve scalar result from query.

Function calls can, like anything else, be composed and nested:

  1. # Get users whose username begins with "A" or "a":
  2. a_users = User.select().where(fn.LOWER(fn.SUBSTR(User.username, 1, 1)) == 'a')

class Window([partition_by=None[, order_by=None[, start=None[, end=None[, frame_type=None[, alias=None]]]]]])

Parameters:
  • partition_by (list) – List of columns to partition by.
  • order_by (list) – List of columns to order by.
  • start – A SQL instance or a string expressing the start of the window range.
  • end – A SQL instance or a string expressing the end of the window range.
  • frame_type (str) – Window.RANGE or Window.ROWS.
  • alias (str) – Alias for the window.

Represent a WINDOW clause.

Note

For an in-depth guide to using window functions with Peewee, see the Window functions section.

  • CURRENT_ROW

    Reference to current row for use in start/end clause.

  • RANGE

    Specify the use of RANGE for the window frame_type. For more information, see Frame types: RANGE vs ROWS.

  • ROWS

    Specify the use of ROWS for the window frame_type. For more information, see Frame types: RANGE vs ROWS.

  • static preceding([value=None])

    Parameters:value – Number of rows preceding. If None is UNBOUNDED.

    Convenience method for generating SQL suitable for passing in as the start parameter for a window range.

  • static following([value=None])

    Parameters:value – Number of rows following. If None is UNBOUNDED.

    Convenience method for generating SQL suitable for passing in as the end parameter for a window range.

  • alias([alias=None])

    Parameters:alias (str) – Alias to use for window.

Case(predicate, expression_tuples[, default=None]])

Parameters:
  • predicate – Predicate for CASE query (optional).
  • expression_tuples – One or more cases to evaluate.
  • default – Default value (optional).
Returns:

Representation of CASE statement.

Examples:

  1. Number = Table('numbers', ('val',))
  2. num_as_str = Case(Number.val, (
  3. (1, 'one'),
  4. (2, 'two'),
  5. (3, 'three')), 'a lot')
  6. query = Number.select(Number.val, num_as_str.alias('num_str'))
  7. # The above is equivalent to:
  8. # SELECT "val",
  9. # CASE "val"
  10. # WHEN 1 THEN 'one'
  11. # WHEN 2 THEN 'two'
  12. # WHEN 3 THEN 'three'
  13. # ELSE 'a lot' END AS "num_str"
  14. # FROM "numbers"
  15. num_as_str = Case(None, (
  16. (Number.val == 1, 'one'),
  17. (Number.val == 2, 'two'),
  18. (Number.val == 3, 'three')), 'a lot')
  19. query = Number.select(Number.val, num_as_str.alias('num_str'))
  20. # The above is equivalent to:
  21. # SELECT "val",
  22. # CASE
  23. # WHEN "val" = 1 THEN 'one'
  24. # WHEN "val" = 2 THEN 'two'
  25. # WHEN "val" = 3 THEN 'three'
  26. # ELSE 'a lot' END AS "num_str"
  27. # FROM "numbers"

class NodeList(nodes[, glue=’ ‘[, parens=False]])

Parameters:
  • nodes (list) – Zero or more nodes.
  • glue (str) – How to join the nodes when converting to SQL.
  • parens (bool) – Whether to wrap the resulting SQL in parentheses.

Represent a list of nodes, a multi-part clause, a list of parameters, etc.

CommaNodeList(nodes)

Parameters:nodes (list) – Zero or more nodes.
Returns:a NodeList

Represent a list of nodes joined by commas.

EnclosedNodeList(nodes)

Parameters:nodes (list) – Zero or more nodes.
Returns:a NodeList

Represent a list of nodes joined by commas and wrapped in parentheses.

class DQ(\*query*)

Parameters:query – Arbitrary filter expressions using Django-style lookups.

Represent a composable Django-style filter expression suitable for use with the Model.filter() or ModelSelect.filter() methods.

class Tuple(\args*)

Represent a SQL row tuple.

class OnConflict([action=None[, update=None[, preserve=None[, where=None[, conflict_target=None]]]]])

Parameters:
  • action (str) – Action to take when resolving conflict.
  • update – A dictionary mapping column to new value.
  • preserve – A list of columns whose values should be preserved from the original INSERT.
  • where – Expression to restrict the conflict resolution.
  • conflict_target – Name of column or constraint to check.

Represent a conflict resolution clause for a data-modification query.

Depending on the database-driver being used, one or more of the above parameters may be required.

  • preserve(\columns*)

    Parameters:columns – Columns whose values should be preserved.
  • update([_data=None[, \*kwargs*]])

    Parameters:
    • _data (dict) – Dictionary mapping column to new value.
    • kwargs – Dictionary mapping column name to new value.

    The update() method supports being called with either a dictionary of column-to-value, or keyword arguments representing the same.

  • where(\expressions*)

    Parameters:expressions – Expressions that restrict the action of the conflict resolution clause.
  • conflict_target(\constraints*)

    Parameters:constraints – Name(s) of columns/constraints that are the target of the conflict resolution.

class BaseQuery

The parent class from which all other query classes are derived. While you will not deal with BaseQuery directly in your code, it implements some methods that are common across all query types.

  • default_row_type = ROW.DICT

  • bind([database=None])

    Parameters:database (Database) – Database to execute query against.

    Bind the query to the given database for execution.

  • dicts([as_dict=True])

    Parameters:as_dict (bool) – Specify whether to return rows as dictionaries.

    Return rows as dictionaries.

  • tuples([as_tuples=True])

    Parameters:as_tuple (bool) – Specify whether to return rows as tuples.

    Return rows as tuples.

  • namedtuples([as_namedtuple=True])

    Parameters:as_namedtuple (bool) – Specify whether to return rows as named tuples.

    Return rows as named tuples.

  • objects([constructor=None])

    Parameters:constructor – Function that accepts row dict and returns an arbitrary object.

    Return rows as arbitrary objects using the given constructor.

  • sql()

    Returns:A 2-tuple consisting of the query’s SQL and parameters.
  • execute(database)

    Parameters:database (Database) – Database to execute query against. Not required if query was previously bound to a database.

    Execute the query and return result (depends on type of query being executed). For example, select queries the return result will be an iterator over the query results.

  • iterator([database=None])

    Parameters:database (Database) – Database to execute query against. Not required if query was previously bound to a database.

    Execute the query and return an iterator over the result-set. For large result-sets this method is preferable as rows are not cached in-memory during iteration.

    Note

    Because rows are not cached, the query may only be iterated over once. Subsequent iterations will return empty result-sets as the cursor will have been consumed.

    Example:

    1. query = StatTbl.select().order_by(StatTbl.timestamp).tuples()
    2. for row in query.iterator(db):
    3. process_row(row)
  • __iter__()

    Execute the query and return an iterator over the result-set.

    Unlike iterator(), this method will cause rows to be cached in order to allow efficient iteration, indexing and slicing.

  • __getitem__(value)

    Parameters:value – Either an integer index or a slice.

    Retrieve a row or range of rows from the result-set.

  • __len__()

    Return the number of rows in the result-set.

    Warning

    This does not issue a COUNT() query. Instead, the result-set is loaded as it would be during normal iteration, and the length is determined from the size of the result set.

class RawQuery([sql=None[, params=None[, \*kwargs*]]])

Parameters:
  • sql (str) – SQL query.
  • params (tuple) – Parameters (optional).

Create a query by directly specifying the SQL to execute.

class Query([where=None[, order_by=None[, limit=None[, offset=None[, \*kwargs*]]]]])

Parameters:
  • where – Representation of WHERE clause.
  • order_by (tuple) – Columns or values to order by.
  • limit (int) – Value of LIMIT clause.
  • offset (int) – Value of OFFSET clause.

Base-class for queries that support method-chaining APIs.

  • with_cte(\cte_list*)

    Parameters:cte_list – zero or more CTE objects.

    Include the given common-table expressions in the query. Any previously specified CTEs will be overwritten. For examples of common-table expressions, see Common Table Expressions.

  • where(\expressions*)

    Parameters:expressions – zero or more expressions to include in the WHERE clause.

    Include the given expressions in the WHERE clause of the query. The expressions will be AND-ed together with any previously-specified WHERE expressions.

    Example selection users where the username is equal to ‘somebody’:

    1. sq = User.select().where(User.username == 'somebody')

    Example selecting tweets made by users who are either editors or administrators:

    1. sq = Tweet.select().join(User).where(
    2. (User.is_editor == True) |
    3. (User.is_admin == True))

    Example of deleting tweets by users who are no longer active:

    1. inactive_users = User.select().where(User.active == False)
    2. dq = (Tweet
    3. .delete()
    4. .where(Tweet.user.in_(inactive_users)))
    5. dq.execute() # Return number of tweets deleted.

    Note

    where() calls are chainable. Multiple calls will be “AND”-ed together.

  • order_by(\values*)

    Parameters:values – zero or more Column-like objects to order by.

    Define the ORDER BY clause. Any previously-specified values will be overwritten.

  • order_by_extend(\values*)

    Parameters:values – zero or more Column-like objects to order by.

    Extend any previously-specified ORDER BY clause with the given values.

  • limit([value=None])

    Parameters:value (int) – specify value for LIMIT clause.
  • offset([value=None])

    Parameters:value (int) – specify value for OFFSET clause.
  • paginate(page[, paginate_by=20])

    Parameters:
    • page (int) – Page number of results (starting from 1).
    • paginate_by (int) – Rows-per-page.

    Convenience method for specifying the LIMIT and OFFSET in a more intuitive way.

    This feature is designed with web-site pagination in mind, so the first page starts with page=1.

class SelectQuery

Select query helper-class that implements operator-overloads for creating compound queries.

  • cte(name[, recursive=False[, columns=None]])

    Parameters:
    • name (str) – Alias for common table expression.
    • recursive (bool) – Will this be a recursive CTE?
    • columns (list) – List of column names (as strings).

    Indicate that a query will be used as a common table expression. For example, if we are modelling a category tree and are using a parent-link foreign key, we can retrieve all categories and their absolute depths using a recursive CTE:

    1. class Category(Model):
    2. name = TextField()
    3. parent = ForeignKeyField('self', backref='children', null=True)
    4. # The base case of our recursive CTE will be categories that are at
    5. # the root level -- in other words, categories without parents.
    6. roots = (Category
    7. .select(Category.name, Value(0).alias('level'))
    8. .where(Category.parent.is_null())
    9. .cte(name='roots', recursive=True))
    10. # The recursive term will select the category name and increment
    11. # the depth, joining on the base term so that the recursive term
    12. # consists of all children of the base category.
    13. RTerm = Category.alias()
    14. recursive = (RTerm
    15. .select(RTerm.name, (roots.c.level + 1).alias('level'))
    16. .join(roots, on=(RTerm.parent == roots.c.id)))
    17. # Express <base term> UNION ALL <recursive term>.
    18. cte = roots.union_all(recursive)
    19. # Select name and level from the recursive CTE.
    20. query = (cte
    21. .select_from(cte.c.name, cte.c.level)
    22. .order_by(cte.c.name))
    23. for category in query:
    24. print(category.name, category.level)

    For more examples of CTEs, see Common Table Expressions.

  • union_all(dest)

    Create a UNION ALL query with dest.

  • __add__(dest)

    Create a UNION ALL query with dest.

  • union(dest)

    Create a UNION query with dest.

  • __or__(dest)

    Create a UNION query with dest.

  • intersect(dest)

    Create an INTERSECT query with dest.

  • __and__(dest)

    Create an INTERSECT query with dest.

  • except_(dest)

    Create an EXCEPT query with dest. Note that the method name has a trailing “_” character since except is a Python reserved word.

  • __sub__(dest)

    Create an EXCEPT query with dest.

class SelectBase

Base-class for Select and CompoundSelect queries.

  • peek(database[, n=1])

    Parameters:
    • database (Database) – database to execute query against.
    • n (int) – Number of rows to return.
    Returns:

    A single row if n = 1, else a list of rows.

    Execute the query and return the given number of rows from the start of the cursor. This function may be called multiple times safely, and will always return the first N rows of results.

  • first(database[, n=1])

    Parameters:
    • database (Database) – database to execute query against.
    • n (int) – Number of rows to return.
    Returns:

    A single row if n = 1, else a list of rows.

    Like the peek() method, except a LIMIT is applied to the query to ensure that only n rows are returned. Multiple calls for the same value of n will not result in multiple executions.

  • scalar(database[, as_tuple=False])

    Parameters:
    • database (Database) – database to execute query against.
    • as_tuple (bool) – Return the result as a tuple?
    Returns:

    Single scalar value if as_tuple = False, else row tuple.

    Return a scalar value from the first row of results. If multiple scalar values are anticipated (e.g. multiple aggregations in a single query) then you may specify as_tuple=True to get the row tuple.

    Example:

    1. query = Note.select(fn.MAX(Note.timestamp))
    2. max_ts = query.scalar(db)
    3. query = Note.select(fn.MAX(Note.timestamp), fn.COUNT(Note.id))
    4. max_ts, n_notes = query.scalar(db, as_tuple=True)
  • count(database[, clear_limit=False])

    Parameters:
    • database (Database) – database to execute query against.
    • clear_limit (bool) – Clear any LIMIT clause when counting.
    Returns:

    Number of rows in the query result-set.

    Return number of rows in the query result-set.

    Implemented by running SELECT COUNT(1) FROM (<current query>).

  • exists(database)

    Parameters:database (Database) – database to execute query against.
    Returns:Whether any results exist for the current query.

    Return a boolean indicating whether the current query has any results.

  • get(database)

    Parameters:database (Database) – database to execute query against.
    Returns:A single row from the database or None.

    Execute the query and return the first row, if it exists. Multiple calls will result in multiple queries being executed.

class CompoundSelectQuery(lhs, op, rhs)

Parameters:
  • lhs (SelectBase) – A Select or CompoundSelect query.
  • op (str) – Operation (e.g. UNION, INTERSECT, EXCEPT).
  • rhs (SelectBase) – A Select or CompoundSelect query.

Class representing a compound SELECT query.

class Select([from_list=None[, columns=None[, group_by=None[, having=None[, distinct=None[, windows=None[, for_update=None[, \*kwargs*]]]]]]]])

Parameters:
  • from_list (list) – List of sources for FROM clause.
  • columns (list) – Columns or values to select.
  • group_by (list) – List of columns or values to group by.
  • having (Expression) – Expression for HAVING clause.
  • distinct – Either a boolean or a list of column-like objects.
  • windows (list) – List of Window clauses.
  • for_update – Boolean or str indicating if SELECT…FOR UPDATE.

Class representing a SELECT query.

Note

Rather than instantiating this directly, most-commonly you will use a factory method like Table.select() or Model.select().

Methods on the select query can be chained together.

Example selecting some user instances from the database. Only the id and username columns are selected. When iterated, will return instances of the User model:

  1. query = User.select(User.id, User.username)
  2. for user in query:
  3. print(user.username)

Example selecting users and additionally the number of tweets made by the user. The User instances returned will have an additional attribute, ‘count’, that corresponds to the number of tweets made:

  1. query = (User
  2. .select(User, fn.COUNT(Tweet.id).alias('count'))
  3. .join(Tweet, JOIN.LEFT_OUTER)
  4. .group_by(User))
  5. for user in query:
  6. print(user.username, 'has tweeted', user.count, 'times')

Note

While it is possible to instantiate Select directly, more commonly you will build the query using the method-chaining APIs.

  • columns(\columns*)

    Parameters:columns – Zero or more column-like objects to SELECT.

    Specify which columns or column-like values to SELECT.

  • select(\columns*)

    Parameters:columns – Zero or more column-like objects to SELECT.

    Same as Select.columns(), provided for backwards-compatibility.

  • select_extend(\columns*)

    Parameters:columns – Zero or more column-like objects to SELECT.

    Extend the current selection with the given columns.

    Example:

    1. def get_users(with_count=False):
    2. query = User.select()
    3. if with_count:
    4. query = (query
    5. .select_extend(fn.COUNT(Tweet.id).alias('count'))
    6. .join(Tweet, JOIN.LEFT_OUTER)
    7. .group_by(User))
    8. return query
  • from_(\sources*)

    Parameters:sources – Zero or more sources for the FROM clause.

    Specify which table-like objects should be used in the FROM clause.

    1. User = Table('users')
    2. Tweet = Table('tweets')
    3. query = (User
    4. .select(User.c.username, Tweet.c.content)
    5. .from_(User, Tweet)
    6. .where(User.c.id == Tweet.c.user_id))
    7. for row in query.execute(db):
    8. print(row['username'], '->', row['content'])
  • join(dest[, join_type=’INNER’[, on=None]])

    Parameters:
    • dest – A table or table-like object.
    • join_type (str) – Type of JOIN, default is “INNER”.
    • on (Expression) – Join predicate.

    Join type may be one of:

    • JOIN.INNER
    • JOIN.LEFT_OUTER
    • JOIN.RIGHT_OUTER
    • JOIN.FULL
    • JOIN.FULL_OUTER
    • JOIN.CROSS

    Express a JOIN:

    1. User = Table('users', ('id', 'username'))
    2. Note = Table('notes', ('id', 'user_id', 'content'))
    3. query = (Note
    4. .select(Note.content, User.username)
    5. .join(User, on=(Note.user_id == User.id)))
  • group_by(\columns*)

    Parameters:values – zero or more Column-like objects to group by.

    Define the GROUP BY clause. Any previously-specified values will be overwritten.

    Additionally, to specify all columns on a given table, you can pass the table/model object in place of the individual columns.

    Example:

    1. query = (User
    2. .select(User, fn.Count(Tweet.id).alias('count'))
    3. .join(Tweet)
    4. .group_by(User))
  • group_by_extend(\columns*)

    Parameters:values – zero or more Column-like objects to group by.

    Extend the GROUP BY clause with the given columns.

  • having(\expressions*)

    Parameters:expressions – zero or more expressions to include in the HAVING clause.

    Include the given expressions in the HAVING clause of the query. The expressions will be AND-ed together with any previously-specified HAVING expressions.

  • distinct(\columns*)

    Parameters:columns – Zero or more column-like objects.

    Indicate whether this query should use a DISTINCT clause. By specifying a single value of True the query will use a simple SELECT DISTINCT. Specifying one or more columns will result in a SELECT DISTINCT ON.

  • window(\windows*)

    Parameters:windows – zero or more Window objects.

    Define the WINDOW clause. Any previously-specified values will be overwritten.

    Example:

    1. # Equivalent example Using a Window() instance instead.
    2. window = Window(partition_by=[Sample.counter])
    3. query = (Sample
    4. .select(
    5. Sample.counter,
    6. Sample.value,
    7. fn.AVG(Sample.value).over(window))
    8. .window(window) # Note call to ".window()"
    9. .order_by(Sample.counter))
  • for_update([for_update=True])

    Parameters:for_update – Either a boolean or a string indicating the desired expression, e.g. “FOR UPDATE NOWAIT”.

class _WriteQuery(table[, returning=None[, \*kwargs*]])

Parameters:
  • table (Table) – Table to write to.
  • returning (list) – List of columns for RETURNING clause.

Base-class for write queries.

  • returning(\returning*)

    Parameters:returning – Zero or more column-like objects for RETURNING clause

    Specify the RETURNING clause of query (if supported by your database).

    1. query = (User
    2. .insert_many([{'username': 'foo'},
    3. {'username': 'bar'},
    4. {'username': 'baz'}])
    5. .returning(User.id, User.username)
    6. .namedtuples())
    7. data = query.execute()
    8. for row in data:
    9. print('added:', row.username, 'with id=', row.id)

class Update(table[, update=None[, \*kwargs*]])

Parameters:
  • table (Table) – Table to update.
  • update (dict) – Data to update.

Class representing an UPDATE query.

Example:

  1. PageView = Table('page_views')
  2. query = (PageView
  3. .update({PageView.c.page_views: PageView.c.page_views + 1})
  4. .where(PageView.c.url == url))
  5. query.execute(database)

class Insert(table[, insert=None[, columns=None[, on_conflict=None[, \*kwargs*]]]])

Parameters:
  • table (Table) – Table to INSERT data into.
  • insert – Either a dict, a list, or a query.
  • columns (list) – List of columns when insert is a list or query.
  • on_conflict – Conflict resolution strategy.

Class representing an INSERT query.

  • on_conflict_ignore([ignore=True])

    Parameters:ignore (bool) – Whether to add ON CONFLICT IGNORE clause.

    Specify IGNORE conflict resolution strategy.

  • on_conflict_replace([replace=True])

    Parameters:ignore (bool) – Whether to add ON CONFLICT REPLACE clause.

    Specify REPLACE conflict resolution strategy.

  • on_conflict([action=None[, update=None[, preserve=None[, where=None[, conflict_target=None]]]]])

    Parameters:
    • action (str) – Action to take when resolving conflict. If blank, action is assumed to be “update”.
    • update – A dictionary mapping column to new value.
    • preserve – A list of columns whose values should be preserved from the original INSERT.
    • where – Expression to restrict the conflict resolution.
    • conflict_target – Name of column or constraint to check.

    Specify the parameters for an OnConflict clause to use for conflict resolution.

    Example:

    1. class User(Model):
    2. username = TextField(unique=True)
    3. last_login = DateTimeField(null=True)
    4. login_count = IntegerField()
    5. def log_user_in(username):
    6. now = datetime.datetime.now()
    7. # INSERT a new row for the user with the current timestamp and
    8. # login count set to 1. If the user already exists, then we
    9. # will preserve the last_login value from the "insert()" clause
    10. # and atomically increment the login-count.
    11. userid = (User
    12. .insert(username=username, last_login=now, login_count=1)
    13. .on_conflict(
    14. conflict_target=[User.username],
    15. preserve=[User.last_login],
    16. update={User.login_count: User.login_count + 1})
    17. .execute())
    18. return userid

class Delete

Class representing a DELETE query.

class Index(name, table, expressions[, unique=False[, safe=False[, where=None[, using=None]]]])

Parameters:
  • name (str) – Index name.
  • table (Table) – Table to create index on.
  • expressions – List of columns to index on (or expressions).
  • unique (bool) – Whether index is UNIQUE.
  • safe (bool) – Whether to add IF NOT EXISTS clause.
  • where (Expression) – Optional WHERE clause for index.
  • using (str) – Index algorithm.
  • safe([_safe=True])

    Parameters:_safe (bool) – Whether to add IF NOT EXISTS clause.
  • where(\expressions*)

    Parameters:expressions – zero or more expressions to include in the WHERE clause.

    Include the given expressions in the WHERE clause of the index. The expressions will be AND-ed together with any previously-specified WHERE expressions.

  • using([_using=None])

    Parameters:_using (str) – Specify index algorithm for USING clause.

class ModelIndex(model, fields[, unique=False[, safe=True[, where=None[, using=None[, name=None]]]]])

Parameters:
  • model (Model) – Model class to create index on.
  • fields (list) – Fields to index.
  • unique (bool) – Whether index is UNIQUE.
  • safe (bool) – Whether to add IF NOT EXISTS clause.
  • where (Expression) – Optional WHERE clause for index.
  • using (str) – Index algorithm.
  • name (str) – Optional index name.

Expressive method for declaring an index on a model.

Examples:

  1. class Article(Model):
  2. name = TextField()
  3. timestamp = TimestampField()
  4. status = IntegerField()
  5. flags = BitField()
  6. is_sticky = flags.flag(1)
  7. is_favorite = flags.flag(2)
  8. # CREATE INDEX ... ON "article" ("name", "timestamp")
  9. idx = ModelIndex(Article, (Article.name, Article.timestamp))
  10. # CREATE INDEX ... ON "article" ("name", "timestamp") WHERE "status" = 1
  11. idx = idx.where(Article.status == 1)
  12. # CREATE UNIQUE INDEX ... ON "article" ("timestamp" DESC, "flags" & 2) WHERE "status" = 1
  13. idx = ModelIndex(
  14. Article,
  15. (Article.timestamp.desc(), Article.flags.bin_and(2)),
  16. unique = True).where(Article.status == 1)

You can also use Model.index():

  1. idx = Article.index(Article.name, Article.timestamp).where(Article.status == 1)

To add an index to a model definition use Model.add_index():

  1. idx = Article.index(Article.name, Article.timestamp).where(Article.status == 1)
  2. # Add above index definition to the model definition. When you call
  3. # Article.create_table() (or database.create_tables([Article])), the
  4. # index will be created.
  5. Article.add_index(idx)

Fields

class Field([null=False[, index=False[, unique=False[, column_name=None[, default=None[, primary_key=False[, constraints=None[, sequence=None[, collation=None[, unindexed=False[, choices=None[, help_text=None[, verbose_name=None]]]]]]]]]]]]])

Parameters:
  • null (bool) – Field allows NULLs.
  • index (bool) – Create an index on field.
  • unique (bool) – Create a unique index on field.
  • column_name (str) – Specify column name for field.
  • default – Default value (enforced in Python, not on server).
  • primary_key (bool) – Field is the primary key.
  • constraints (list) – List of constraints to apply to column, for example: [Check(‘price > 0’)].
  • sequence (str) – Sequence name for field.
  • collation (str) – Collation name for field.
  • unindexed (bool) – Declare field UNINDEXED (sqlite only).
  • choices (list) – An iterable of 2-tuples mapping column values to display labels. Used for metadata purposes only, to help when displaying a dropdown of choices for field values, for example.
  • help_text (str) – Help-text for field, metadata purposes only.
  • verbose_name (str) – Verbose name for field, metadata purposes only.

Fields on a Model are analogous to columns on a table.

  • field_type = '<some field type>'

    Attribute used to map this field to a column type, e.g. “INT”. See the FIELD object in the source for more information.

  • column

    Retrieve a reference to the underlying Column object.

  • model

    The model the field is bound to.

  • name

    The name of the field.

  • db_value(value)

    Coerce a Python value into a value suitable for storage in the database. Sub-classes operating on special data-types will most likely want to override this method.

  • python_value(value)

    Coerce a value from the database into a Python object. Sub-classes operating on special data-types will most likely want to override this method.

  • coerce(value)

    This method is a shorthand that is used, by default, by both db_value() and python_value().

    Parameters:value – arbitrary data from app or backend
    Return type:python data type

class IntegerField

Field class for storing integers.

class BigIntegerField

Field class for storing big integers (if supported by database).

class SmallIntegerField

Field class for storing small integers (if supported by database).

class AutoField

Field class for storing auto-incrementing primary keys.

Note

In SQLite, for performance reasons, the default primary key type simply uses the max existing value + 1 for new values, as opposed to the max ever value + 1. This means deleted records can have their primary keys reused. In conjunction with SQLite having foreign keys disabled by default (meaning ON DELETE is ignored, even if you specify it explicitly), this can lead to surprising and dangerous behaviour. To avoid this, you may want to use one or both of AutoIncrementField and pragmas=[('foreign_keys', 'on')] when you instantiate SqliteDatabase.

class BigAutoField

Field class for storing auto-incrementing primary keys using 64-bits.

class IdentityField

Field class for storing auto-incrementing primary keys using the new Postgres 10 IDENTITY column type. The column definition ends up looking like this:

  1. id = IdentityField()
  2. # "id" INT GENERATED BY DEFAULT AS IDENTITY NOT NULL PRIMARY KEY

Attention

Only supported by Postgres 10.0 and newer.

class FloatField

Field class for storing floating-point numbers.

class DoubleField

Field class for storing double-precision floating-point numbers.

class DecimalField([max_digits=10[, decimal_places=5[, auto_round=False[, rounding=None[, \*kwargs*]]]]])

Parameters:
  • max_digits (int) – Maximum digits to store.
  • decimal_places (int) – Maximum precision.
  • auto_round (bool) – Automatically round values.
  • rounding

    Defaults to decimal.DefaultContext.rounding.

    Field class for storing decimal numbers. Values are represented as decimal.Decimal objects.

class CharField([max_length=255])

Field class for storing strings.

Note

Values that exceed length are not truncated automatically.

class FixedCharField

Field class for storing fixed-length strings.

Note

Values that exceed length are not truncated automatically.

class TextField

Field class for storing text.

class BlobField

Field class for storing binary data.

class BitField

Field class for storing options in a 64-bit integer column.

Usage:

  1. class Post(Model):
  2. content = TextField()
  3. flags = BitField()
  4. is_favorite = flags.flag(1)
  5. is_sticky = flags.flag(2)
  6. is_minimized = flags.flag(4)
  7. is_deleted = flags.flag(8)
  8. >>> p = Post()
  9. >>> p.is_sticky = True
  10. >>> p.is_minimized = True
  11. >>> print(p.flags) # Prints 4 | 2 --> "6"
  12. 6
  13. >>> p.is_favorite
  14. False
  15. >>> p.is_sticky
  16. True

We can use the flags on the Post class to build expressions in queries as well:

  1. # Generates a WHERE clause that looks like:
  2. # WHERE (post.flags & 1 != 0)
  3. query = Post.select().where(Post.is_favorite)
  4. # Query for sticky + favorite posts:
  5. query = Post.select().where(Post.is_sticky & Post.is_favorite)
  • flag([value=None])

    Parameters:value (int) – Value associated with flag, typically a power of 2.

    Returns a descriptor that can get or set specific bits in the overall value. When accessed on the class itself, it returns a Expression object suitable for use in a query.

    If the value is not provided, it is assumed that each flag will be an increasing power of 2, so if you had four flags, they would have the values 1, 2, 4, 8.

class BigBitField

Field class for storing arbitrarily-large bitmaps in a BLOB. The field will grow the underlying buffer as necessary, ensuring there are enough bytes of data to support the number of bits of data being stored.

Example usage:

  1. class Bitmap(Model):
  2. data = BigBitField()
  3. bitmap = Bitmap()
  4. # Sets the ith bit, e.g. the 1st bit, the 11th bit, the 63rd, etc.
  5. bits_to_set = (1, 11, 63, 31, 55, 48, 100, 99)
  6. for bit_idx in bits_to_set:
  7. bitmap.data.set_bit(bit_idx)
  8. # We can test whether a bit is set using "is_set":
  9. assert bitmap.data.is_set(11)
  10. assert not bitmap.data.is_set(12)
  11. # We can clear a bit:
  12. bitmap.data.clear_bit(11)
  13. assert not bitmap.data.is_set(11)
  14. # We can also "toggle" a bit. Recall that the 63rd bit was set earlier.
  15. assert bitmap.data.toggle_bit(63) is False
  16. assert bitmap.data.toggle_bit(63) is True
  17. assert bitmap.data.is_set(63)
  • set_bit(idx)

    Parameters:idx (int) – Bit to set, indexed starting from zero.

    Sets the idx-th bit in the bitmap.

  • clear_bit(idx)

    Parameters:idx (int) – Bit to clear, indexed starting from zero.

    Clears the idx-th bit in the bitmap.

  • toggle_bit(idx)

    Parameters:idx (int) – Bit to toggle, indexed starting from zero.
    Returns:Whether the bit is set or not.

    Toggles the idx-th bit in the bitmap and returns whether the bit is set or not.

    Example:

    1. >>> bitmap = Bitmap()
    2. >>> bitmap.data.toggle_bit(10) # Toggle the 10th bit.
    3. True
    4. >>> bitmap.data.toggle_bit(10) # This will clear the 10th bit.
    5. False
  • is_set(idx)

    Parameters:idx (int) – Bit index, indexed starting from zero.
    Returns:Whether the bit is set or not.

    Returns boolean indicating whether the idx-th bit is set or not.

class UUIDField

Field class for storing uuid.UUID objects. With Postgres, the underlying column’s data-type will be UUID. Since SQLite and MySQL do not have a native UUID type, the UUID is stored as a VARCHAR instead.

class BinaryUUIDField

Field class for storing uuid.UUID objects efficiently in 16-bytes. Uses the database’s BLOB data-type (or VARBINARY in MySQL, or BYTEA in Postgres).

class DateTimeField([formats=None[, \*kwargs*]])

Parameters:formats (list) – A list of format strings to use when coercing a string to a date-time.

Field class for storing datetime.datetime objects.

Accepts a special parameter formats, which contains a list of formats the datetime can be encoded with (for databases that do not have support for a native datetime data-type). The default supported formats are:

  1. '%Y-%m-%d %H:%M:%S.%f' # year-month-day hour-minute-second.microsecond
  2. '%Y-%m-%d %H:%M:%S' # year-month-day hour-minute-second
  3. '%Y-%m-%d' # year-month-day

Note

SQLite does not have a native datetime data-type, so datetimes are stored as strings. This is handled transparently by Peewee, but if you have pre-existing data you should ensure it is stored as YYYY-mm-dd HH:MM:SS or one of the other supported formats.

  • year

    Reference the year of the value stored in the column in a query.

    1. Blog.select().where(Blog.pub_date.year == 2018)
  • month

    Reference the month of the value stored in the column in a query.

  • day

    Reference the day of the value stored in the column in a query.

  • hour

    Reference the hour of the value stored in the column in a query.

  • minute

    Reference the minute of the value stored in the column in a query.

  • second

    Reference the second of the value stored in the column in a query.

class DateField([formats=None[, \*kwargs*]])

Parameters:formats (list) – A list of format strings to use when coercing a string to a date.

Field class for storing datetime.date objects.

Accepts a special parameter formats, which contains a list of formats the datetime can be encoded with (for databases that do not have support for a native date data-type). The default supported formats are:

  1. '%Y-%m-%d' # year-month-day
  2. '%Y-%m-%d %H:%M:%S' # year-month-day hour-minute-second
  3. '%Y-%m-%d %H:%M:%S.%f' # year-month-day hour-minute-second.microsecond

Note

If the incoming value does not match a format, it is returned as-is.

  • year

    Reference the year of the value stored in the column in a query.

    1. Person.select().where(Person.dob.year == 1983)
  • month

    Reference the month of the value stored in the column in a query.

  • day

    Reference the day of the value stored in the column in a query.

class TimeField([formats=None[, \*kwargs*]])

Parameters:formats (list) – A list of format strings to use when coercing a string to a time.

Field class for storing datetime.time objects (not timedelta).

Accepts a special parameter formats, which contains a list of formats the datetime can be encoded with (for databases that do not have support for a native time data-type). The default supported formats are:

  1. '%H:%M:%S.%f' # hour:minute:second.microsecond
  2. '%H:%M:%S' # hour:minute:second
  3. '%H:%M' # hour:minute
  4. '%Y-%m-%d %H:%M:%S.%f' # year-month-day hour-minute-second.microsecond
  5. '%Y-%m-%d %H:%M:%S' # year-month-day hour-minute-second

Note

If the incoming value does not match a format, it is returned as-is.

  • hour

    Reference the hour of the value stored in the column in a query.

    1. evening_events = Event.select().where(Event.time.hour > 17)
  • minute

    Reference the minute of the value stored in the column in a query.

  • second

    Reference the second of the value stored in the column in a query.

class TimestampField([resolution=1[, utc=False[, \*kwargs*]]])

Parameters:
  • resolution – A power of 10, 1=second, 1000=ms, 1000000=us, etc.
  • utc (bool) – Treat timestamps as UTC.

Field class for storing date-times as integer timestamps. Sub-second resolution is supported by multiplying by a power of 10 to get an integer.

Accepts a special parameter resolution, which is a power-of-10 up to 10^6. This allows sub-second precision while still using an IntegerField for storage. Default is 1 (second precision).

Also accepts a boolean parameter utc, used to indicate whether the timestamps should be UTC. Default is False.

Finally, the field default is the current timestamp. If you do not want this behavior, then explicitly pass in default=None.

class IPField

Field class for storing IPv4 addresses efficiently (as integers).

class BooleanField

Field class for storing boolean values.

class BareField([coerce=None[, \*kwargs*]])

Parameters:coerce – Optional function to use for converting raw values into a specific format.

Field class that does not specify a data-type (SQLite-only).

Since data-types are not enforced, you can declare fields without any data-type. It is also common for SQLite virtual tables to use meta-columns or untyped columns, so for those cases as well you may wish to use an untyped field.

Accepts a special coerce parameter, a function that takes a value coming from the database and converts it into the appropriate Python type.

class ForeignKeyField(model[, field=None[, backref=None[, on_delete=None[, on_update=None[, deferrable=None[, object_id_name=None[, \*kwargs*]]]]]]])

Parameters:
  • model (Model) – Model to reference or the string ‘self’ if declaring a self-referential foreign key.
  • field (Field) – Field to reference on model (default is primary key).
  • backref (str) – Accessor name for back-reference.
  • on_delete (str) – ON DELETE action, e.g. ‘CASCADE’..
  • on_update (str) – ON UPDATE action.
  • deferrable (str) – Control when constraint is enforced, e.g. ‘INITIALLY DEFERRED’.
  • object_id_name (str) – Name for object-id accessor.

Field class for storing a foreign key.

  1. class User(Model):
  2. name = TextField()
  3. class Tweet(Model):
  4. user = ForeignKeyField(User, backref='tweets')
  5. content = TextField()
  6. # "user" attribute
  7. >>> some_tweet.user
  8. <User: charlie>
  9. # "tweets" backref attribute
  10. >>> for tweet in charlie.tweets:
  11. ... print(tweet.content)
  12. Some tweet
  13. Another tweet
  14. Yet another tweet

For an in-depth discussion of foreign-keys, joins and relationships between models, refer to Relationships and Joins.

Note

Foreign keys do not have a particular field_type as they will take their field type depending on the type of primary key on the model they are related to.

Note

If you manually specify a field, that field must be either a primary key or have a unique constraint.

Note

Take care with foreign keys in SQLite. By default, ON DELETE has no effect, which can have surprising (and usually unwanted) effects on your database integrity. This can affect you even if you don’t specify on_delete, since the default ON DELETE behaviour (to fail without modifying your data) does not happen, and your data can be silently relinked. The safest thing to do is to specify pragmas={'foreign_keys': 1} when you instantiate SqliteDatabase.

class DeferredForeignKey(rel_model_name[, \*kwargs*])

Parameters:rel_model_name (str) – Model name to reference.

Field class for representing a deferred foreign key. Useful for circular foreign-key references, for example:

  1. class Husband(Model):
  2. name = TextField()
  3. wife = DeferredForeignKey('Wife', deferrable='INITIALLY DEFERRED')
  4. class Wife(Model):
  5. name = TextField()
  6. husband = ForeignKeyField(Husband, deferrable='INITIALLY DEFERRED')

In the above example, when the Wife model is declared, the foreign-key Husband.wife is automatically resolved and turned into a regular ForeignKeyField.

class ManyToManyField(model[, backref=None[, through_model=None]])

Parameters:
  • model (Model) – Model to create relationship with.
  • backref (str) – Accessor name for back-reference
  • through_model (Model) – Model to use for the intermediary table. If not provided, a simple through table will be automatically created.

The ManyToManyField provides a simple interface for working with many-to-many relationships, inspired by Django. A many-to-many relationship is typically implemented by creating a junction table with foreign keys to the two models being related. For instance, if you were building a syllabus manager for college students, the relationship between students and courses would be many-to-many. Here is the schema using standard APIs:

Attention

This is not a field in the sense that there is no column associated with it. Rather, it provides a convenient interface for accessing rows of data related via a through model.

Standard way of declaring a many-to-many relationship (without the use of the ManyToManyField):

  1. class Student(Model):
  2. name = CharField()
  3. class Course(Model):
  4. name = CharField()
  5. class StudentCourse(Model):
  6. student = ForeignKeyField(Student)
  7. course = ForeignKeyField(Course)

To query the courses for a particular student, you would join through the junction table:

  1. # List the courses that "Huey" is enrolled in:
  2. courses = (Course
  3. .select()
  4. .join(StudentCourse)
  5. .join(Student)
  6. .where(Student.name == 'Huey'))
  7. for course in courses:
  8. print(course.name)

The ManyToManyField is designed to simplify this use-case by providing a field-like API for querying and modifying data in the junction table. Here is how our code looks using ManyToManyField:

  1. class Student(Model):
  2. name = CharField()
  3. class Course(Model):
  4. name = CharField()
  5. students = ManyToManyField(Student, backref='courses')

Note

It does not matter from Peewee’s perspective which model the ManyToManyField goes on, since the back-reference is just the mirror image. In order to write valid Python, though, you will need to add the ManyToManyField on the second model so that the name of the first model is in the scope.

We still need a junction table to store the relationships between students and courses. This model can be accessed by calling the get_through_model() method. This is useful when creating tables.

  1. # Create tables for the students, courses, and relationships between
  2. # the two.
  3. db.create_tables([
  4. Student,
  5. Course,
  6. Course.students.get_through_model()])

When accessed from a model instance, the ManyToManyField exposes a ModelSelect representing the set of related objects. Let’s use the interactive shell to see how all this works:

  1. >>> huey = Student.get(Student.name == 'huey')
  2. >>> [course.name for course in huey.courses]
  3. ['English 101', 'CS 101']
  4. >>> engl_101 = Course.get(Course.name == 'English 101')
  5. >>> [student.name for student in engl_101.students]
  6. ['Huey', 'Mickey', 'Zaizee']

To add new relationships between objects, you can either assign the objects directly to the ManyToManyField attribute, or call the add() method. The difference between the two is that simply assigning will clear out any existing relationships, whereas add() can preserve existing relationships.

  1. >>> huey.courses = Course.select().where(Course.name.contains('english'))
  2. >>> for course in huey.courses.order_by(Course.name):
  3. ... print course.name
  4. English 101
  5. English 151
  6. English 201
  7. English 221
  8. >>> cs_101 = Course.get(Course.name == 'CS 101')
  9. >>> cs_151 = Course.get(Course.name == 'CS 151')
  10. >>> huey.courses.add([cs_101, cs_151])
  11. >>> [course.name for course in huey.courses.order_by(Course.name)]
  12. ['CS 101', 'CS151', 'English 101', 'English 151', 'English 201',
  13. 'English 221']

This is quite a few courses, so let’s remove the 200-level english courses. To remove objects, use the remove() method.

  1. >>> huey.courses.remove(Course.select().where(Course.name.contains('2'))
  2. 2
  3. >>> [course.name for course in huey.courses.order_by(Course.name)]
  4. ['CS 101', 'CS151', 'English 101', 'English 151']

To remove all relationships from a collection, you can use the clear() method. Let’s say that English 101 is canceled, so we need to remove all the students from it:

  1. >>> engl_101 = Course.get(Course.name == 'English 101')
  2. >>> engl_101.students.clear()

Note

For an overview of implementing many-to-many relationships using standard Peewee APIs, check out the Implementing Many to Many section. For all but the most simple cases, you will be better off implementing many-to-many using the standard APIs.

  • through_model

    The Model representing the many-to-many junction table. Will be auto-generated if not explicitly declared.

  • add(value[, clear_existing=True])

    Parameters:
    • value – Either a Model instance, a list of model instances, or a SelectQuery.
    • clear_existing (bool) – Whether to remove existing relationships.

    Associate value with the current instance. You can pass in a single model instance, a list of model instances, or even a ModelSelect.

    Example code:

    1. # Huey needs to enroll in a bunch of courses, including all
    2. # the English classes, and a couple Comp-Sci classes.
    3. huey = Student.get(Student.name == 'Huey')
    4. # We can add all the objects represented by a query.
    5. english_courses = Course.select().where(
    6. Course.name.contains('english'))
    7. huey.courses.add(english_courses)
    8. # We can also add lists of individual objects.
    9. cs101 = Course.get(Course.name == 'CS 101')
    10. cs151 = Course.get(Course.name == 'CS 151')
    11. huey.courses.add([cs101, cs151])
  • remove(value)

    Parameters:value – Either a Model instance, a list of model instances, or a ModelSelect.

    Disassociate value from the current instance. Like add(), you can pass in a model instance, a list of model instances, or even a ModelSelect.

    Example code:

    1. # Huey is currently enrolled in a lot of english classes
    2. # as well as some Comp-Sci. He is changing majors, so we
    3. # will remove all his courses.
    4. english_courses = Course.select().where(
    5. Course.name.contains('english'))
    6. huey.courses.remove(english_courses)
    7. # Remove the two Comp-Sci classes Huey is enrolled in.
    8. cs101 = Course.get(Course.name == 'CS 101')
    9. cs151 = Course.get(Course.name == 'CS 151')
    10. huey.courses.remove([cs101, cs151])
  • clear()

    Remove all associated objects.

    Example code:

    1. # English 101 is canceled this semester, so remove all
    2. # the enrollments.
    3. english_101 = Course.get(Course.name == 'English 101')
    4. english_101.students.clear()
  • get_through_model()

    Return the Model representing the many-to-many junction table. This can be specified manually when the field is being instantiated using the through_model parameter. If a through_model is not specified, one will automatically be created.

    When creating tables for an application that uses ManyToManyField, you must create the through table expicitly.

    1. # Get a reference to the automatically-created through table.
    2. StudentCourseThrough = Course.students.get_through_model()
    3. # Create tables for our two models as well as the through model.
    4. db.create_tables([
    5. Student,
    6. Course,
    7. StudentCourseThrough])

class DeferredThroughModel

Place-holder for a through-model in cases where, due to a dependency, you cannot declare either a model or a many-to-many field without introducing NameErrors.

Example:

  1. class Note(BaseModel):
  2. content = TextField()
  3. NoteThroughDeferred = DeferredThroughModel()
  4. class User(BaseModel):
  5. username = TextField()
  6. notes = ManyToManyField(Note, through_model=NoteThroughDeferred)
  7. # Cannot declare this before "User" since it has a foreign-key to
  8. # the User model.
  9. class NoteThrough(BaseModel):
  10. note = ForeignKeyField(Note)
  11. user = ForeignKeyField(User)
  12. # Resolve dependencies.
  13. NoteThroughDeferred.set_model(NoteThrough)

class CompositeKey(\field_names*)

Parameters:field_names – Names of fields that comprise the primary key.

A primary key composed of multiple columns. Unlike the other fields, a composite key is defined in the model’s Meta class after the fields have been defined. It takes as parameters the string names of the fields to use as the primary key:

  1. class BlogTagThrough(Model):
  2. blog = ForeignKeyField(Blog, backref='tags')
  3. tag = ForeignKeyField(Tag, backref='blogs')
  4. class Meta:
  5. primary_key = CompositeKey('blog', 'tag')

Schema Manager

class SchemaManager(model[, database=None[, \*context_options*]])

Parameters:
  • model (Model) – Model class.
  • database (Database) – If unspecified defaults to model._meta.database.

Provides methods for managing the creation and deletion of tables and indexes for the given model.

  • create_table([safe=True[, \*options*]])

    Parameters:
    • safe (bool) – Specify IF NOT EXISTS clause.
    • options – Arbitrary options.

    Execute CREATE TABLE query for the given model.

  • drop_table([safe=True[, drop_sequences=True[, \*options*]]])

    Parameters:
    • safe (bool) – Specify IF EXISTS clause.
    • drop_sequences (bool) – Drop any sequences associated with the columns on the table (postgres only).
    • options – Arbitrary options.

    Execute DROP TABLE query for the given model.

  • create_indexes([safe=True])

    Parameters:safe (bool) – Specify IF NOT EXISTS clause.

    Execute CREATE INDEX queries for the indexes defined for the model.

  • drop_indexes([safe=True])

    Parameters:safe (bool) – Specify IF EXISTS clause.

    Execute DROP INDEX queries for the indexes defined for the model.

  • create_sequence(field)

    Parameters:field (Field) – Field instance which specifies a sequence.

    Create sequence for the given Field.

  • drop_sequence(field)

    Parameters:field (Field) – Field instance which specifies a sequence.

    Drop sequence for the given Field.

  • create_foreign_key(field)

    Parameters:field (ForeignKeyField) – Foreign-key field constraint to add.

    Add a foreign-key constraint for the given field. This method should not be necessary in most cases, as foreign-key constraints are created as part of table creation. The exception is when you are creating a circular foreign-key relationship using DeferredForeignKey. In those cases, it is necessary to first create the tables, then add the constraint for the deferred foreign-key:

    1. class Language(Model):
    2. name = TextField()
    3. selected_snippet = DeferredForeignKey('Snippet')
    4. class Snippet(Model):
    5. code = TextField()
    6. language = ForeignKeyField(Language, backref='snippets')
    7. # Creates both tables but does not create the constraint for the
    8. # Language.selected_snippet foreign key (because of the circular
    9. # dependency).
    10. db.create_tables([Language, Snippet])
    11. # Explicitly create the constraint:
    12. Language._schema.create_foreign_key(Language.selected_snippet)

    For more information, see documentation on Circular foreign key dependencies.

    Warning

    Because SQLite has limited support for altering existing tables, it is not possible to add a foreign-key constraint to an existing SQLite table.

  • create_all([safe=True[, \*table_options*]])

    Parameters:safe (bool) – Whether to specify IF NOT EXISTS.

    Create sequence(s), index(es) and table for the model.

  • drop_all([safe=True[, drop_sequences=True[, \*options*]]])

    Parameters:
    • safe (bool) – Whether to specify IF EXISTS.
    • drop_sequences (bool) – Drop any sequences associated with the columns on the table (postgres only).
    • options – Arbitrary options.

    Drop table for the model and associated indexes.

Model

class Metadata(model[, database=None[, table_name=None[, indexes=None[, primary_key=None[, constraints=None[, schema=None[, only_save_dirty=False[, table_alias=None[, depends_on=None[, options=None[, without_rowid=False[, \*kwargs*]]]]]]]]]]]])

Parameters:
  • model (Model) – Model class.
  • database (Database) – database model is bound to.
  • table_name (str) – Specify table name for model.
  • indexes (list) – List of ModelIndex objects.
  • primary_key – Primary key for model (only specified if this is a CompositeKey or False for no primary key.
  • constraints (list) – List of table constraints.
  • schema (str) – Schema table exists in.
  • only_save_dirty (bool) – When save() is called, only save the fields which have been modified.
  • table_alias (str) – Specify preferred alias for table in queries.
  • options (dict) – Arbitrary options for the model.
  • without_rowid (bool) – Specify WITHOUT ROWID (sqlite only).
  • kwargs – Arbitrary setting attributes and values.

Store metadata for a Model.

This class should not be instantiated directly, but is instantiated using the attributes of a Model class’ inner Meta class. Metadata attributes are then available on Model._meta.

  • table

    Return a reference to the underlying Table object.

  • model_graph([refs=True[, backrefs=True[, depth_first=True]]])

    Parameters:
    • refs (bool) – Follow foreign-key references.
    • backrefs (bool) – Follow foreign-key back-references.
    • depth_first (bool) – Do a depth-first search (False for breadth-first).

    Traverse the model graph and return a list of 3-tuples, consisting of (foreign key field, model class, is_backref).

class SubclassAwareMetadata

Metadata subclass that tracks Model subclasses.

  • map_models(fn)

    Apply a function to all subclasses.

class Model(\*kwargs*)

Parameters:kwargs – Mapping of field-name to value to initialize model with.

Model class provides a high-level abstraction for working with database tables. Models are a one-to-one mapping with a database table (or a table-like object, such as a view). Subclasses of Model declare any number of Field instances as class attributes. These fields correspond to columns on the table.

Table-level operations, such as select(), update(), insert() and delete() are implemented as classmethods. Row-level operations, such as save() and delete_instance() are implemented as instancemethods.

Example:

  1. db = SqliteDatabase(':memory:')
  2. class User(Model):
  3. username = TextField()
  4. join_date = DateTimeField(default=datetime.datetime.now)
  5. is_admin = BooleanField(default=False)
  6. admin = User(username='admin', is_admin=True)
  7. admin.save()
  • classmethod alias([alias=None])

    Parameters:alias (str) – Optional name for alias.
    Returns:ModelAlias instance.

    Create an alias to the model-class. Model aliases allow you to reference the same Model multiple times in a query, for example when doing a self-join or sub-query.

    Example:

    1. Parent = Category.alias()
    2. sq = (Category
    3. .select(Category, Parent)
    4. .join(Parent, on=(Category.parent == Parent.id))
    5. .where(Parent.name == 'parent category'))
  • classmethod select(\fields*)

    Parameters:fields – A list of model classes, field instances, functions or expressions. If no arguments are provided, all columns for the given model will be selected by default.
    Returns:ModelSelect query.

    Create a SELECT query. If no fields are explicitly provided, the query will by default SELECT all the fields defined on the model, unless you are using the query as a sub-query, in which case only the primary key will be selected by default.

    Example of selecting all columns:

    1. query = User.select().where(User.active == True).order_by(User.username)

    Example of selecting all columns on Tweet and the parent model, User. When the user foreign key is accessed on a Tweet instance no additional query will be needed (see N+1 for more details):

    1. query = (Tweet
    2. .select(Tweet, User)
    3. .join(User)
    4. .order_by(Tweet.created_date.desc()))
    5. for tweet in query:
    6. print(tweet.user.username, '->', tweet.content)

    Example of subquery only selecting the primary key:

    1. inactive_users = User.select().where(User.active == False)
    2. # Here, instead of defaulting to all columns, Peewee will default
    3. # to only selecting the primary key.
    4. Tweet.delete().where(Tweet.user.in_(inactive_users)).execute()
  • classmethod update([__data=None[, \*update*]])

    Parameters:
    • __data (dict) – dict of fields to values.
    • update – Field-name to value mapping.

    Create an UPDATE query.

    Example showing users being marked inactive if their registration has expired:

    1. q = (User
    2. .update({User.active: False})
    3. .where(User.registration_expired == True))
    4. q.execute() # Execute the query, returning number of rows updated.

    Example showing an atomic update:

    1. q = (PageView
    2. .update({PageView.count: PageView.count + 1})
    3. .where(PageView.url == url))
    4. q.execute() # Execute the query.

    Note

    When an update query is executed, the number of rows modified will be returned.

  • classmethod insert([__data=None[, \*insert*]])

    Parameters:
    • __data (dict) – dict of fields to values to insert.
    • insert – Field-name to value mapping.

    Create an INSERT query.

    Insert a new row into the database. If any fields on the model have default values, these values will be used if the fields are not explicitly set in the insert dictionary.

    Example showing creation of a new user:

    1. q = User.insert(username='admin', active=True, registration_expired=False)
    2. q.execute() # perform the insert.

    You can also use Field objects as the keys:

    1. new_id = User.insert({User.username: 'admin'}).execute()

    If you have a model with a default value on one of the fields, and that field is not specified in the insert parameter, the default will be used:

    1. class User(Model):
    2. username = CharField()
    3. active = BooleanField(default=True)
    4. # This INSERT query will automatically specify `active=True`:
    5. User.insert(username='charlie')

    Note

    When an insert query is executed on a table with an auto-incrementing primary key, the primary key of the new row will be returned.

  • classmethod insert_many(rows[, fields=None])

    Parameters:
    • rows – An iterable that yields rows to insert.
    • fields (list) – List of fields being inserted.

    INSERT multiple rows of data.

    The rows parameter must be an iterable that yields dictionaries or tuples, where the ordering of the tuple values corresponds to the fields specified in the fields argument. As with insert(), fields that are not specified in the dictionary will use their default value, if one exists.

    Note

    Due to the nature of bulk inserts, each row must contain the same fields. The following will not work:

    1. Person.insert_many([
    2. {'first_name': 'Peewee', 'last_name': 'Herman'},
    3. {'first_name': 'Huey'}, # Missing "last_name"!
    4. ]).execute()

    Example of inserting multiple Users:

    1. data = [
    2. ('charlie', True),
    3. ('huey', False),
    4. ('zaizee', False)]
    5. query = User.insert_many(data, fields=[User.username, User.is_admin])
    6. query.execute()

    Equivalent example using dictionaries:

    1. data = [
    2. {'username': 'charlie', 'is_admin': True},
    3. {'username': 'huey', 'is_admin': False},
    4. {'username': 'zaizee', 'is_admin': False}]
    5. # Insert new rows.
    6. User.insert_many(data).execute()

    Because the rows parameter can be an arbitrary iterable, you can also use a generator:

    1. def get_usernames():
    2. for username in ['charlie', 'huey', 'peewee']:
    3. yield {'username': username}
    4. User.insert_many(get_usernames()).execute()

    Warning

    If you are using SQLite, your SQLite library must be version 3.7.11 or newer to take advantage of bulk inserts.

    Note

    SQLite has a default limit of 999 bound variables per statement. This limit can be modified at compile-time or at run-time, but if modifying at run-time, you can only specify a lower value than the default limit.

    For more information, check out the following SQLite documents:

  • classmethod insert_from(query, fields)

    Parameters:
    • query (Select) – SELECT query to use as source of data.
    • fields – Fields to insert data into.

    INSERT data using a SELECT query as the source. This API should be used for queries of the form INSERT INTO … SELECT FROM ….

    Example of inserting data across tables for denormalization purposes:

    1. source = (User
    2. .select(User.username, fn.COUNT(Tweet.id))
    3. .join(Tweet, JOIN.LEFT_OUTER)
    4. .group_by(User.username))
    5. UserTweetDenorm.insert_from(
    6. source,
    7. [UserTweetDenorm.username, UserTweetDenorm.num_tweets]).execute()
  • classmethod replace([__data=None[, \*insert*]])

    Parameters:
    • __data (dict) – dict of fields to values to insert.
    • insert – Field-name to value mapping.

    Create an INSERT query that uses REPLACE for conflict-resolution.

    See Model.insert() for examples.

  • classmethod replace_many(rows[, fields=None])

    Parameters:
    • rows – An iterable that yields rows to insert.
    • fields (list) – List of fields being inserted.

    INSERT multiple rows of data using REPLACE for conflict-resolution.

    See Model.insert_many() for examples.

  • classmethod raw(sql, \params*)

    Parameters:
    • sql (str) – SQL query to execute.
    • params – Parameters for query.

    Execute a SQL query directly.

    Example selecting rows from the User table:

    1. q = User.raw('select id, username from users')
    2. for user in q:
    3. print(user.id, user.username)

    Note

    Generally the use of raw is reserved for those cases where you can significantly optimize a select query. It is useful for select queries since it will return instances of the model.

  • classmethod delete()

    Create a DELETE query.

    Example showing the deletion of all inactive users:

    1. q = User.delete().where(User.active == False)
    2. q.execute() # Remove the rows, return number of rows removed.

    Warning

    This method performs a delete on the entire table. To delete a single instance, see Model.delete_instance().

  • classmethod create(\*query*)

    Parameters:query – Mapping of field-name to value.

    INSERT new row into table and return corresponding model instance.

    Example showing the creation of a user (a row will be added to the database):

    1. user = User.create(username='admin', password='test')

    Note

    The create() method is a shorthand for instantiate-then-save.

  • classmethod get(\query, **filters*)

    Parameters:
    • query – Zero or more Expression objects.
    • filters – Mapping of field-name to value for Django-style filter.
    Raises:

    DoesNotExist

    Returns:

    Model instance matching the specified filters.

    Retrieve a single model instance matching the given filters. If no model is returned, a DoesNotExist is raised.

    1. user = User.get(User.username == username, User.active == True)

    This method is also exposed via the SelectQuery, though it takes no parameters:

    1. active = User.select().where(User.active == True)
    2. try:
    3. user = active.where(
    4. (User.username == username) &
    5. (User.active == True)
    6. ).get()
    7. except User.DoesNotExist:
    8. user = None

    Note

    The get() method is shorthand for selecting with a limit of 1. It has the added behavior of raising an exception when no matching row is found. If more than one row is found, the first row returned by the database cursor will be used.

  • classmethod get_or_none(\query, **filters*)

    Identical to Model.get() but returns None if no model matches the given filters.

  • classmethod get_by_id(pk)

    Parameters:pk – Primary-key value.

    Short-hand for calling Model.get() specifying a lookup by primary key. Raises a DoesNotExist if instance with the given primary key value does not exist.

    Example:

    1. user = User.get_by_id(1) # Returns user with id = 1.
  • classmethod set_by_id(key, value)

    Parameters:
    • key – Primary-key value.
    • value (dict) – Mapping of field to value to update.

    Short-hand for updating the data with the given primary-key. If no row exists with the given primary key, no exception will be raised.

    Example:

    1. # Set "is_admin" to True on user with id=3.
    2. User.set_by_id(3, {'is_admin': True})
  • classmethod delete_by_id(pk)

    Parameters:pk – Primary-key value.

    Short-hand for deleting the row with the given primary-key. If no row exists with the given primary key, no exception will be raised.

  • classmethod get_or_create(\*kwargs*)

    Parameters:
    • kwargs – Mapping of field-name to value.
    • defaults – Default values to use if creating a new row.
    Returns:

    Tuple of Model instance and boolean indicating if a new object was created.

    Attempt to get the row matching the given filters. If no matching row is found, create a new row.

    Warning

    Race-conditions are possible when using this method.

    Example without get_or_create:

    1. # Without `get_or_create`, we might write:
    2. try:
    3. person = Person.get(
    4. (Person.first_name == 'John') &
    5. (Person.last_name == 'Lennon'))
    6. except Person.DoesNotExist:
    7. person = Person.create(
    8. first_name='John',
    9. last_name='Lennon',
    10. birthday=datetime.date(1940, 10, 9))

    Equivalent code using get_or_create:

    1. person, created = Person.get_or_create(
    2. first_name='John',
    3. last_name='Lennon',
    4. defaults={'birthday': datetime.date(1940, 10, 9)})
  • classmethod filter(\dq_nodes, **filters*)

    Parameters:
    • dq_nodes – Zero or more DQ objects.
    • filters – Django-style filters.
    Returns:

    ModelSelect query.

  • get_id()

    Returns:The primary-key of the model instance.
  • save([force_insert=False[, only=None]])

    Parameters:
    • force_insert (bool) – Force INSERT query.
    • only (list) – Only save the given Field instances.
    Returns:

    Number of rows modified.

    Save the data in the model instance. By default, the presence of a primary-key value will cause an UPDATE query to be executed.

    Example showing saving a model instance:

    1. user = User()
    2. user.username = 'some-user' # does not touch the database
    3. user.save() # change is persisted to the db
  • dirty_fields

    Return list of fields that have been modified.

    Return type:list

    Note

    If you just want to persist modified fields, you can call model.save(only=model.dirty_fields).

    If you always want to only save a model’s dirty fields, you can use the Meta option only_save_dirty = True. Then, any time you call Model.save(), by default only the dirty fields will be saved, e.g.

    1. class Person(Model):
    2. first_name = CharField()
    3. last_name = CharField()
    4. dob = DateField()
    5. class Meta:
    6. database = db
    7. only_save_dirty = True
  • is_dirty()

    Return boolean indicating whether any fields were manually set.

  • delete_instance([recursive=False[, delete_nullable=False]])

    Parameters:
    • recursive (bool) – Delete related models.
    • delete_nullable (bool) – Delete related models that have a null foreign key. If False nullable relations will be set to NULL.

    Delete the given instance. Any foreign keys set to cascade on delete will be deleted automatically. For more programmatic control, you can specify recursive=True, which will delete any non-nullable related models (those that are nullable will be set to NULL). If you wish to delete all dependencies regardless of whether they are nullable, set delete_nullable=True.

    example:

    1. some_obj.delete_instance() # it is gone forever
  • classmethod bind(database[, bind_refs=True[, bind_backrefs=True]])

    Parameters:
    • database (Database) – database to bind to.
    • bind_refs (bool) – Bind related models.
    • bind_backrefs (bool) – Bind back-reference related models.

    Bind the model (and specified relations) to the given database.

    See also: Database.bind().

  • classmethod bind_ctx(database[, bind_refs=True[, bind_backrefs=True]])

    Like bind(), but returns a context manager that only binds the models for the duration of the wrapped block.

    See also: Database.bind_ctx().

  • classmethod table_exists()

    Returns:boolean indicating whether the table exists.
  • classmethod create_table([safe=True[, \*options*]])

    Parameters:safe (bool) – If set to True, the create table query will include an IF NOT EXISTS clause.

    Create the model table, indexes, constraints and sequences.

    Example:

    1. with database:
    2. SomeModel.create_table() # Execute the create table query.
  • classmethod drop_table([safe=True[, \*options*]])

    Parameters:safe (bool) – If set to True, the create table query will include an IF EXISTS clause.

    Drop the model table.

  • classmethod index(\fields[, unique=False[, safe=True[, where=None[, using=None[, name=None*]]]]])

    Parameters:
    • fields – Fields to index.
    • unique (bool) – Whether index is UNIQUE.
    • safe (bool) – Whether to add IF NOT EXISTS clause.
    • where (Expression) – Optional WHERE clause for index.
    • using (str) – Index algorithm.
    • name (str) – Optional index name.

    Expressive method for declaring an index on a model. Wraps the declaration of a ModelIndex instance.

    Examples:

    1. class Article(Model):
    2. name = TextField()
    3. timestamp = TimestampField()
    4. status = IntegerField()
    5. flags = BitField()
    6. is_sticky = flags.flag(1)
    7. is_favorite = flags.flag(2)
    8. # CREATE INDEX ... ON "article" ("name", "timestamp" DESC)
    9. idx = Article.index(Article.name, Article.timestamp.desc())
    10. # Be sure to add the index to the model:
    11. Article.add_index(idx)
    12. # CREATE UNIQUE INDEX ... ON "article" ("timestamp" DESC, "flags" & 2)
    13. # WHERE ("status" = 1)
    14. idx = (Article
    15. .index(Article.timestamp.desc(),
    16. Article.flags.bin_and(2),
    17. unique=True)
    18. .where(Article.status == 1))
    19. # Add index to model:
    20. Article.add_index(idx)
  • classmethod add_index(\args, **kwargs*)

    Parameters:
    • args – a ModelIndex instance, Field(s) to index, or a SQL instance that contains the SQL for creating the index.
    • kwargs – Keyword arguments passed to ModelIndex constructor.

    Add an index to the model’s definition.

    Note

    This method does not actually create the index in the database. Rather, it adds the index definition to the model’s metadata, so that a subsequent call to create_table() will create the new index (along with the table).

    Examples:

    1. class Article(Model):
    2. name = TextField()
    3. timestamp = TimestampField()
    4. status = IntegerField()
    5. flags = BitField()
    6. is_sticky = flags.flag(1)
    7. is_favorite = flags.flag(2)
    8. # CREATE INDEX ... ON "article" ("name", "timestamp") WHERE "status" = 1
    9. idx = Article.index(Article.name, Article.timestamp).where(Article.status == 1)
    10. Article.add_index(idx)
    11. # CREATE UNIQUE INDEX ... ON "article" ("timestamp" DESC, "flags" & 2)
    12. ts_flags_idx = Article.index(
    13. Article.timestamp.desc(),
    14. Article.flags.bin_and(2),
    15. unique=True)
    16. Article.add_index(ts_flags_idx)
    17. # You can also specify a list of fields and use the same keyword
    18. # arguments that the ModelIndex constructor accepts:
    19. Article.add_index(
    20. Article.name,
    21. Article.timestamp.desc(),
    22. where=(Article.status == 1))
    23. # Or even specify a SQL query directly:
    24. Article.add_index(SQL('CREATE INDEX ...'))
  • dependencies([search_nullable=False])

    Parameters:search_nullable (bool) – Search models related via a nullable foreign key
    Return type:Generator expression yielding queries and foreign key fields.

    Generate a list of queries of dependent models. Yields a 2-tuple containing the query and corresponding foreign key field. Useful for searching dependencies of a model, i.e. things that would be orphaned in the event of a delete.

  • __iter__()

    Returns:a ModelSelect for the given class.

    Convenience function for iterating over all instances of a model.

    Example:

    1. Setting.insert_many([
    2. {'key': 'host', 'value': '192.168.1.2'},
    3. {'key': 'port': 'value': '1337'},
    4. {'key': 'user': 'value': 'nuggie'}]).execute()
    5. # Load settings from db into dict.
    6. settings = {setting.key: setting.value for setting in Setting}
  • __len__()

    Returns:Count of rows in table.

    Example:

    1. n_accounts = len(Account)
    2. # Is equivalent to:
    3. n_accounts = Account.select().count()

class ModelAlias(model[, alias=None])

Parameters:
  • model (Model) – Model class to reference.
  • alias (str) – (optional) name for alias.

Provide a separate reference to a model in a query.

class ModelSelect(model, fields_or_models)

Parameters:
  • model (Model) – Model class to select.
  • fields_or_models – List of fields or model classes to select.

Model-specific implementation of SELECT query.

  • switch([ctx=None])

    Parameters:ctx – A Model, ModelAlias, subquery, or other object that was joined-on.

    Switch the join context - the source which subsequent calls to join() will be joined against. Used for specifying multiple joins against a single table.

    If the ctx is not given, then the query’s model will be used.

    The following example selects from tweet and joins on both user and tweet-flag:

    1. sq = Tweet.select().join(User).switch(Tweet).join(TweetFlag)
    2. # Equivalent (since Tweet is the query's model)
    3. sq = Tweet.select().join(User).switch().join(TweetFlag)
  • objects([constructor=None])

    Parameters:constructor – Constructor (defaults to returning model instances)

    Return result rows as objects created using the given constructor. The default behavior is to create model instances.

    Note

    This method can be used, when selecting field data from multiple sources/models, to make all data available as attributes on the model being queried (as opposed to constructing the graph of joined model instances). For very complex queries this can have a positive performance impact, especially iterating large result sets.

    Similarly, you can use dicts(), tuples() or namedtuples() to achieve even more performance.

  • join(dest[, join_type=’INNER’[, on=None[, src=None[, attr=None]]]])

    Parameters:
    • dest – A Model, ModelAlias, Select query, or other object to join to.
    • join_type (str) – Join type, defaults to INNER.
    • on – Join predicate or a ForeignKeyField to join on.
    • src – Explicitly specify the source of the join. If not specified then the current join context will be used.
    • attr (str) – Attribute to use when projecting columns from the joined model.

    Join with another table-like object.

    Join type may be one of:

    • JOIN.INNER
    • JOIN.LEFT_OUTER
    • JOIN.RIGHT_OUTER
    • JOIN.FULL
    • JOIN.FULL_OUTER
    • JOIN.CROSS

    Example selecting tweets and joining on user in order to restrict to only those tweets made by “admin” users:

    1. sq = Tweet.select().join(User).where(User.is_admin == True)

    Example selecting users and joining on a particular foreign key field. See the example app for a real-life usage:

    1. sq = User.select().join(Relationship, on=Relationship.to_user)

    For an in-depth discussion of foreign-keys, joins and relationships between models, refer to Relationships and Joins.

  • join_from(src, dest[, join_type=’INNER’[, on=None[, attr=None]]])

    Parameters:
    • src – Source for join.
    • dest – Table to join to.

    Use same parameter order as the non-model-specific join(). Bypasses the join context by requiring the join source to be specified.

  • filter(\args, **kwargs*)

    Parameters:
    • args – Zero or more DQ objects.
    • kwargs – Django-style keyword-argument filters.

    Use Django-style filters to express a WHERE clause.

  • prefetch(\subqueries*)

    Parameters:subqueries – A list of Model classes or select queries to prefetch.

    Execute the query, prefetching the given additional resources.

    See also prefetch() standalone function.

    Example:

    1. # Fetch all Users and prefetch their associated tweets.
    2. query = User.select().prefetch(Tweet)
    3. for user in query:
    4. print(user.username)
    5. for tweet in user.tweets:
    6. print(' *', tweet.content)

prefetch(sq, \subqueries*)

Parameters:
  • sq – Query to use as starting-point.
  • subqueries – One or more models or ModelSelect queries to eagerly fetch.

Eagerly fetch related objects, allowing efficient querying of multiple tables when a 1-to-many relationship exists.

For example, it is simple to query a many-to-1 relationship efficiently:

  1. query = (Tweet
  2. .select(Tweet, User)
  3. .join(User))
  4. for tweet in query:
  5. # Looking up tweet.user.username does not require a query since
  6. # the related user's columns were selected.
  7. print(tweet.user.username, '->', tweet.content)

To efficiently do the inverse, query users and their tweets, you can use prefetch:

  1. query = User.select()
  2. for user in prefetch(query, Tweet):
  3. print(user.username)
  4. for tweet in user.tweets: # Does not require additional query.
  5. print(' ', tweet.content)

Query-builder Internals

class AliasManager

Manages the aliases assigned to Source objects in SELECT queries, so as to avoid ambiguous references when multiple sources are used in a single query.

  • add(source)

    Add a source to the AliasManager’s internal registry at the current scope. The alias will be automatically generated using the following scheme (where each level of indentation refers to a new scope):

    Parameters:source (Source) – Make the manager aware of a new source. If the source has already been added, the call is a no-op.
  • get(source[, any_depth=False])

    Return the alias for the source in the current scope. If the source does not have an alias, it will be given the next available alias.

    Parameters:source (Source) – The source whose alias should be retrieved.
    Returns:The alias already assigned to the source, or the next available alias.
    Return type:str
  • __setitem__(source, alias)

    Manually set the alias for the source at the current scope.

    Parameters:source (Source) – The source for which we set the alias.
  • push()

    Push a new scope onto the stack.

  • pop()

    Pop scope from the stack.

class State(scope[, parentheses=False[, subquery=False[, \*kwargs*]]])

Lightweight object for representing the state at a given scope. During SQL generation, each object visited by the Context can inspect the state. The State class allows Peewee to do things like:

  • Use a common interface for field types or SQL expressions, but use vendor-specific data-types or operators.
  • Compile a Column instance into a fully-qualified attribute, as a named alias, etc, depending on the value of the scope.
  • Ensure parentheses are used appropriately.
Parameters:
  • scope (int) – The scope rules to be applied while the state is active.
  • parentheses (bool) – Wrap the contained SQL in parentheses.
  • subquery (bool) – Whether the current state is a child of an outer query.
  • kwargs (dict) – Arbitrary settings which should be applied in the current state.

class Context(\*settings*)

Converts Peewee structures into parameterized SQL queries.

Peewee structures should all implement a __sql__ method, which will be called by the Context class during SQL generation. The __sql__ method accepts a single parameter, the Context instance, which allows for recursive descent and introspection of scope and state.

  • scope

    Return the currently-active scope rules.

  • parentheses

    Return whether the current state is wrapped in parentheses.

  • subquery

    Return whether the current state is the child of another query.

  • scope_normal([\*kwargs*])

    The default scope. Sources are referred to by alias, columns by dotted-path from the source.

  • scope_source([\*kwargs*])

    Scope used when defining sources, e.g. in the column list and FROM clause of a SELECT query. This scope is used for defining the fully-qualified name of the source and assigning an alias.

  • scope_values([\*kwargs*])

    Scope used for UPDATE, INSERT or DELETE queries, where instead of referencing a source by an alias, we refer to it directly. Similarly, since there is a single table, columns do not need to be referenced by dotted-path.

  • scope_cte([\*kwargs*])

    Scope used when generating the contents of a common-table-expression. Used after a WITH statement, when generating the definition for a CTE (as opposed to merely a reference to one).

  • scope_column([\*kwargs*])

    Scope used when generating SQL for a column. Ensures that the column is rendered with it’s correct alias. Was needed because when referencing the inner projection of a sub-select, Peewee would render the full SELECT query as the “source” of the column (instead of the query’s alias + . + column). This scope allows us to avoid rendering the full query when we only need the alias.

  • sql(obj)

    Append a composable Node object, sub-context, or other object to the query AST. Python values, such as integers, strings, floats, etc. are treated as parameterized values.

    Returns:The updated Context object.
  • literal(keyword)

    Append a string-literal to the current query AST.

    Returns:The updated Context object.
  • parse(node)

    Parameters:node (Node) – Instance of a Node subclass.
    Returns:a 2-tuple consisting of (sql, parameters).

    Convert the given node to a SQL AST and return a 2-tuple consisting of the SQL query and the parameters.

  • query()

    Returns:a 2-tuple consisting of (sql, parameters) for the context.

Constants and Helpers

class Proxy

Create a proxy or placeholder for another object.

  • initialize(obj)

    Parameters:obj – Object to proxy to.

    Bind the proxy to the given object. Afterwards all attribute lookups and method calls on the proxy will be sent to the given object.

    Any callbacks that have been registered will be called.

  • attach_callback(callback)

    Parameters:callback – A function that accepts a single parameter, the bound object.
    Returns:self

    Add a callback to be executed when the proxy is initialized.