Model

  • class Metadata(model[, database=None[, table_name=None[, indexes=None[, primary_key=None[, constraints=None[, schema=None[, only_save_dirty=False[, 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 aCompositeKey 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, onlysave the fields which have been modified.
  • 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 usingthe attributes of a Model class’ inner Meta class. Metadataattributes are then available on Model._meta.

  • table
  • Return a reference to the underlying Table object.

  • modelgraph([_refs=True[, backrefs=True[, depth_first=True]]])

Parameters:

  1. - **refs** (_bool_) Follow foreign-key references.
  2. - **backrefs** (_bool_) Follow foreign-key back-references.
  3. - **depth_first** (_bool_) Do a depth-first search (<code>False</code> forbreadth-first).

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

  • setdatabase(_database)

Parameters:database (Database) – database object to bind Model to.

Bind the model class to the given Database instance.

Warning

This API should not need to be used. Instead, to change aModel database at run-time, use one of the following:

  1. - [<code>Model.bind()</code>](#Model.bind)
  2. - [<code>Model.bind_ctx()</code>](#Model.bind_ctx) (bind for scope of a context manager).
  3. - [<code>Database.bind()</code>](#Database.bind)
  4. - [<code>Database.bind_ctx()</code>](#Database.bind_ctx)
  • settable_name(_table_name)

Parameters:table_name (str) – table name to bind Model to.

Bind the model class to the given table name at run-time.

  • class SubclassAwareMetadata
  • Metadata subclass that tracks Model subclasses.

    • mapmodels(_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 databasetables. Models are a one-to-one mapping with a database table (or atable-like object, such as a view). Subclasses of Model declare anynumber of Field instances as class attributes. These fieldscorrespond to columns on the table.

Table-level operations, such as select(),update(), insert() anddelete() are implemented as classmethods. Row-leveloperations, such as save() anddelete_instance() are implemented as instancemethods.

Example:

  1. db = SqliteDatabase(':memory:')
  2.  
  3. class User(Model):
  4. username = TextField()
  5. join_date = DateTimeField(default=datetime.datetime.now)
  6. is_admin = BooleanField(default=False)
  7.  
  8. admin = User(username='admin', is_admin=True)
  9. 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 toreference the same Model multiple times in a query, forexample 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 orexpressions. If no arguments are provided, all columns for thegiven model will be selected by default.Returns:ModelSelect query.

Create a SELECT query. If no fields are explicitly provided, the querywill by default SELECT all the fields defined on the model, unless youare using the query as a sub-query, in which case only the primary keywill 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+1for more details):

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

Example of subquery only selecting the primary key:

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

Parameters:

  1. - **__data** (_dict_) <code>dict</code> of fields to values.
  2. - **update** Field-name to value mapping.

Create an UPDATE query.

Example showing users being marked inactive if their registration hasexpired:

  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 willbe returned.

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

Parameters:

  1. - **__data** (_dict_) <code>dict</code> of fields to values to insert.
  2. - **insert** Field-name to value mapping.

Create an INSERT query.

Insert a new row into the database. If any fields on the model havedefault values, these values will be used if the fields are notexplicitly 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, andthat field is not specified in the insert parameter, the defaultwill be used:

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

Note

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

  • classmethod insertmany(_rows[, fields=None])

Parameters:

  1. - **rows** An iterable that yields rows to insert.
  2. - **fields** (_list_) List of fields being inserted.Returns:

number of rows modified (see note).

INSERT multiple rows of data.

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

Note

Due to the nature of bulk inserts, each row must contain the samefields. 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.  
  6. # Insert new rows.
  7. User.insert_many(data).execute()

Because the rows parameter can be an arbitrary iterable, you canalso 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.11or 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, butif modifying at run-time, you can only specify a lower value thanthe default limit.

For more information, check out the following SQLite documents:

  1. - [Max variable number limit](https://www.sqlite.org/limits.html#max_variable_number)
  2. - [Changing run-time limits](https://www.sqlite.org/c3ref/limit.html)
  3. - [SQLite compile-time flags](https://www.sqlite.org/compile.html)

Note

The default return value is the number of rows modified. However,when using Postgres, Peewee will return a cursor by default thatyields the primary-keys of the inserted rows. To disable thisfunctionality with Postgres, use an empty call to returning().

  • classmethod insertfrom(_query, fields)

Parameters:

  1. - **query** ([_Select_](#Select)) SELECT query to use as source of data.
  2. - **fields** Fields to insert data into.Returns:

number of rows modified (see note).

INSERT data using a SELECT query as the source. This API should be usedfor 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.  
  6. UserTweetDenorm.insert_from(
  7. source,
  8. [UserTweetDenorm.username, UserTweetDenorm.num_tweets]).execute()

Note

The default return value is the number of rows modified. However,when using Postgres, Peewee will return a cursor by default thatyields the primary-keys of the inserted rows. To disable thisfunctionality with Postgres, use an empty call to returning().

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

Parameters:

  1. - **__data** (_dict_) <code>dict</code> of fields to values to insert.
  2. - **insert** Field-name to value mapping.

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

See Model.insert() for examples.

  • classmethod replacemany(_rows[, fields=None])

Parameters:

  1. - **rows** An iterable that yields rows to insert.
  2. - **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:

  1. - **sql** (_str_) SQL query to execute.
  2. - **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 youcan significantly optimize a select query. It is useful for selectqueries 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 asingle 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 thedatabase):

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

Note

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

  • classmethod bulkcreate(_model_list[, batch_size=None])

Parameters:

  1. - **model_list** (_iterable_) a list or other iterable of unsaved[<code>Model</code>](#Model) instances.
  2. - **batch_size** (_int_) number of rows to batch per insert. Ifunspecified, all models will be inserted in a single query.Returns:

no return value.

Efficiently INSERT multiple unsaved model instances into the database.Unlike insert_many(), which accepts row data as a listof either dictionaries or lists, this method accepts a list of unsavedmodel instances.

Example:

  1. # List of 10 unsaved users.
  2. user_list = [User(username='u%s' % i) for i in range(10)]
  3.  
  4. # All 10 users are inserted in a single query.
  5. User.bulk_create(user_list)

Batches:

  1. user_list = [User(username='u%s' % i) for i in range(10)]
  2.  
  3. with database.atomic():
  4. # Will execute 4 INSERT queries (3 batches of 3, 1 batch of 1).
  5. User.bulk_create(user_list, batch_size=3)

Warning

  1. - The primary-key value for the newly-created models will only beset if you are using Postgresql (which supports the <code>RETURNING</code>clause).
  2. - SQLite generally has a limit of 999 bound parameters for a query,so the batch size should be roughly 1000 / number-of-fields.
  3. - When a batch-size is provided it is **strongly recommended** thatyou wrap the call in a transaction or savepoint using[<code>Database.atomic()</code>](#Database.atomic). Otherwise an error in a batch mid-waythrough could leave the database in an inconsistent state.
  • classmethod bulkupdate(_model_list, fields[, batch_size=None])

Parameters:

  1. - **model_list** (_iterable_) a list or other iterable of[<code>Model</code>](#Model) instances.
  2. - **fields** (_list_) list of fields to update.
  3. - **batch_size** (_int_) number of rows to batch per insert. Ifunspecified, all models will be inserted in a single query.Returns:

total number of rows updated.

Efficiently UPDATE multiple model instances.

Example:

  1. # First, create 3 users.
  2. u1, u2, u3 = [User.create(username='u%s' % i) for i in (1, 2, 3)]
  3.  
  4. # Now let's modify their usernames.
  5. u1.username = 'u1-x'
  6. u2.username = 'u2-y'
  7. u3.username = 'u3-z'
  8.  
  9. # Update all three rows using a single UPDATE query.
  10. User.bulk_update([u1, u2, u3], fields=[User.username])

If you have a large number of objects to update, it is stronglyrecommended that you specify a batch_size and wrap the operation ina transaction:

  1. with database.atomic():
  2. User.bulk_update(user_list, fields=['username'], batch_size=50)

Warning

  1. - SQLite generally has a limit of 999 bound parameters for a query.
  2. - When a batch-size is provided it is **strongly recommended** thatyou wrap the call in a transaction or savepoint using[<code>Database.atomic()</code>](#Database.atomic). Otherwise an error in a batch mid-waythrough could leave the database in an inconsistent state.
  • classmethod get(*query, **filters)

Parameters:

  1. - **query** Zero or more [<code>Expression</code>](#Expression) objects.
  2. - **filters** Mapping of field-name to value for Django-style filter.Raises:

DoesNotExistReturns:Model instance matching the specified filters.

Retrieve a single model instance matching the given filters. If nomodel 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 ittakes 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 alimit of 1. It has the added behavior of raising an exception whenno matching row is found. If more than one row is found, the firstrow returned by the database cursor will be used.

  • classmethod getor_none(query, *filters_)
  • Identical to Model.get() but returns None if no modelmatches the given filters.

  • classmethod getby_id(_pk)

Parameters:pk – Primary-key value.

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

Example:

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

Parameters:

  1. - **key** Primary-key value.
  2. - **value** (_dict_) Mapping of field to value to update.

Short-hand for updating the data with the given primary-key. If no rowexists 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 deleteby_id(_pk)

Parameters:pk – Primary-key value.

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

  • classmethod getor_create(**kwargs_)

Parameters:

  1. - **kwargs** Mapping of field-name to value.
  2. - **defaults** Default values to use if creating a new row.Returns:

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

Attempt to get the row matching the given filters. If no matching rowis 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:

  1. - **dq_nodes** Zero or more [<code>DQ</code>](#DQ) objects.
  2. - **filters** Django-style filters.Returns:

ModelSelect query.

  • get_id()

Returns:The primary-key of the model instance.

  • save([force_insert=False[, only=None]])

Parameters:

  1. - **force_insert** (_bool_) Force INSERT query.
  2. - **only** (_list_) Only save the given [<code>Field</code>](#Field) instances.Returns:

Number of rows modified.

Save the data in the model instance. By default, the presence of aprimary-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 callmodel.save(only=model.dirty_fields).

If you always want to only save a model’s dirty fields, you can use the Metaoption 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.  
  6. class Meta:
  7. database = db
  8. only_save_dirty = True

Warning

Peewee determines whether a field is “dirty” by observing when thefield attribute is set on a model instance. If the field contains avalue that is mutable, such as a dictionary instance, and thatdictionary is then modified, Peewee will not notice the change.

  • is_dirty()
  • Return boolean indicating whether any fields were manually set.

  • deleteinstance([_recursive=False[, delete_nullable=False]])

Parameters:

  1. - **recursive** (_bool_) Delete related models.
  2. - **delete_nullable** (_bool_) Delete related models that have a nullforeign key. If <code>False</code> nullable relations will be set to NULL.

Delete the given instance. Any foreign keys set to cascade ondelete will be deleted automatically. For more programmatic control,you can specify recursive=True, which will delete any non-nullablerelated models (those that are nullable will be set to NULL). If youwish 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:

  1. - **database** ([_Database_](#Database)) database to bind to.
  2. - **bind_refs** (_bool_) Bind related models.
  3. - **bind_backrefs** (_bool_) Bind back-reference related models.

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

See also: Database.bind().

  • classmethod bindctx(_database[, bind_refs=True[, bind_backrefs=True]])
  • Like bind(), but returns a context manager that onlybinds 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 createtable([_safe=True[, **options]])

Parameters:safe (bool) – If set to True, the create table query willinclude 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 droptable([_safe=True[, **options]])

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

Drop the model table.

  • truncatetable([_restart_identity=False[, cascade=False]])

Parameters:

  1. - **restart_identity** (_bool_) Restart the id sequence (postgres-only).
  2. - **cascade** (_bool_) Truncate related tables as well (postgres-only).

Truncate (delete all rows) for the model.

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

Parameters:

  1. - **fields** Fields to index.
  2. - **unique** (_bool_) Whether index is UNIQUE.
  3. - **safe** (_bool_) Whether to add IF NOT EXISTS clause.
  4. - **where** ([_Expression_](#Expression)) Optional WHERE clause for index.
  5. - **using** (_str_) Index algorithm.
  6. - **name** (_str_) Optional index name.

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

Examples:

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

Parameters:

  1. - **args** a [<code>ModelIndex</code>](#ModelIndex) instance, Field(s) to index,or a [<code>SQL</code>](#SQL) instance that contains the SQL for creatingthe index.
  2. - **kwargs** Keyword arguments passed to [<code>ModelIndex</code>](#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, sothat a subsequent call to create_table() willcreate 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.  
  7. is_sticky = flags.flag(1)
  8. is_favorite = flags.flag(2)
  9.  
  10. # CREATE INDEX ... ON "article" ("name", "timestamp") WHERE "status" = 1
  11. idx = Article.index(Article.name, Article.timestamp).where(Article.status == 1)
  12. Article.add_index(idx)
  13.  
  14. # CREATE UNIQUE INDEX ... ON "article" ("timestamp" DESC, "flags" & 2)
  15. ts_flags_idx = Article.index(
  16. Article.timestamp.desc(),
  17. Article.flags.bin_and(2),
  18. unique=True)
  19. Article.add_index(ts_flags_idx)
  20.  
  21. # You can also specify a list of fields and use the same keyword
  22. # arguments that the ModelIndex constructor accepts:
  23. Article.add_index(
  24. Article.name,
  25. Article.timestamp.desc(),
  26. where=(Article.status == 1))
  27.  
  28. # Or even specify a SQL query directly:
  29. Article.add_index(SQL('CREATE INDEX ...'))
  • dependencies([search_nullable=False])

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

Generate a list of queries of dependent models. Yields a 2-tuplecontaining the query and corresponding foreign key field. Useful forsearching dependencies of a model, i.e. things that would be orphanedin 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.  
  6. # Load settings from db into dict.
  7. settings = {setting.key: setting.value for setting in Setting}
  • len()

Returns:Count of rows in table.

Example:

  1. n_accounts = len(Account)
  2.  
  3. # Is equivalent to:
  4. 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, orother object that was joined-on.

Switch the join context - the source which subsequent calls tojoin() will be joined against. Used forspecifying 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 andtweet-flag:

  1. sq = Tweet.select().join(User).switch(Tweet).join(TweetFlag)
  2.  
  3. # Equivalent (since Tweet is the query's model)
  4. 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. Thedefault behavior is to create model instances.

Note

This method can be used, when selecting field data from multiplesources/models, to make all data available as attributes on themodel being queried (as opposed to constructing the graph of joinedmodel instances). For very complex queries this can have a positiveperformance 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:

  1. - **dest** A [<code>Model</code>](#Model), [<code>ModelAlias</code>](#ModelAlias),[<code>Select</code>](#Select) query, or other object to join to.
  2. - **join_type** (_str_) Join type, defaults to INNER.
  3. - **on** Join predicate or a [<code>ForeignKeyField</code>](#ForeignKeyField) to join on.
  4. - **src** Explicitly specify the source of the join. If not specifiedthen the current _join context_ will be used.
  5. - **attr** (_str_) Attribute to use when projecting columns from thejoined model.

Join with another table-like object.

Join type may be one of:

  1. - <code>JOIN.INNER</code>
  2. - <code>JOIN.LEFT_OUTER</code>
  3. - <code>JOIN.RIGHT_OUTER</code>
  4. - <code>JOIN.FULL</code>
  5. - <code>JOIN.FULL_OUTER</code>
  6. - <code>JOIN.CROSS</code>

Example selecting tweets and joining on user in order to restrict toonly 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 relationshipsbetween models, refer to Relationships and Joins.

  • joinfrom(_src, dest[, join_type='INNER'[, on=None[, attr=None]]])

Parameters:

  1. - **src** Source for join.
  2. - **dest** Table to join to.

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

  • filter(*args, **kwargs)

Parameters:

  1. - **args** Zero or more [<code>DQ</code>](#DQ) objects.
  2. - **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 selectqueries to prefetch.Returns:a list of models with selected relations prefetched.

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 queriesto eagerly fetch.Returns:a list of models with selected relations prefetched.

Eagerly fetch related objects, allowing efficient querying of multipletables 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 useprefetch:

  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)