Querying

This section will cover the basic CRUD operations commonly performed on a relational database:

Creating a new record

You can use Model.create() to create a new model instance. This method accepts keyword arguments, where the keys correspond to the names of the model’s fields. A new instance is returned and a row is added to the table.

  1. >>> User.create(username='Charlie')
  2. <__main__.User object at 0x2529350>

This will INSERT a new row into the database. The primary key will automatically be retrieved and stored on the model instance.

Alternatively, you can build up a model instance programmatically and then call save():

  1. >>> user = User(username='Charlie')
  2. >>> user.save() # save() returns the number of rows modified.
  3. 1
  4. >>> user.id
  5. 1
  6. >>> huey = User()
  7. >>> huey.username = 'Huey'
  8. >>> huey.save()
  9. 1
  10. >>> huey.id
  11. 2

When a model has a foreign key, you can directly assign a model instance to the foreign key field when creating a new record.

  1. >>> tweet = Tweet.create(user=huey, message='Hello!')

You can also use the value of the related object’s primary key:

  1. >>> tweet = Tweet.create(user=2, message='Hello again!')

If you simply wish to insert data and do not need to create a model instance, you can use Model.insert():

  1. >>> User.insert(username='Mickey').execute()
  2. 3

After executing the insert query, the primary key of the new row is returned.

Note

There are several ways you can speed up bulk insert operations. Check out the Bulk inserts recipe section for more information.

Bulk inserts

There are a couple of ways you can load lots of data quickly. The naive approach is to simply call Model.create() in a loop:

  1. data_source = [
  2. {'field1': 'val1-1', 'field2': 'val1-2'},
  3. {'field1': 'val2-1', 'field2': 'val2-2'},
  4. # ...
  5. ]
  6. for data_dict in data_source:
  7. Model.create(**data_dict)

The above approach is slow for a couple of reasons:

  1. If you are using autocommit (the default), then each call to create() happens in its own transaction. That is going to be really slow!
  2. There is a decent amount of Python logic getting in your way, and each InsertQuery must be generated and parsed into SQL.
  3. That’s a lot of data (in terms of raw bytes of SQL) you are sending to your database to parse.
  4. We are retrieving the last insert id, which causes an additional query to be executed in some cases.

You can get a very significant speedup by simply wrapping this in a atomic().

  1. # This is much faster.
  2. with db.atomic():
  3. for data_dict in data_source:
  4. Model.create(**data_dict)

The above code still suffers from points 2, 3 and 4. We can get another big boost by calling insert_many(). This method accepts a list of dictionaries to insert.

  1. # Fastest.
  2. with db.atomic():
  3. Model.insert_many(data_source).execute()

Depending on the number of rows in your data source, you may need to break it up into chunks:

  1. # Insert rows 100 at a time.
  2. with db.atomic():
  3. for idx in range(0, len(data_source), 100):
  4. Model.insert_many(data_source[idx:idx+100]).execute()

Note

SQLite users should be aware of some caveats when using bulk inserts. Specifically, your SQLite3 version must be 3.7.11.0 or newer to take advantage of the bulk insert API. Additionally, by default SQLite limits the number of bound variables in a SQL query to 999. This value can be modified by setting the SQLITE_MAX_VARIABLE_NUMBER flag.

If the data you would like to bulk load is stored in another table, you can also create INSERT queries whose source is a SELECT query. Use the Model.insert_from() method:

  1. query = (TweetArchive
  2. .insert_from(
  3. fields=[Tweet.user, Tweet.message],
  4. query=Tweet.select(Tweet.user, Tweet.message))
  5. .execute())

Updating existing records

Once a model instance has a primary key, any subsequent call to save() will result in an UPDATE rather than another INSERT. The model’s primary key will not change:

  1. >>> user.save() # save() returns the number of rows modified.
  2. 1
  3. >>> user.id
  4. 1
  5. >>> user.save()
  6. >>> user.id
  7. 1
  8. >>> huey.save()
  9. 1
  10. >>> huey.id
  11. 2

If you want to update multiple records, issue an UPDATE query. The following example will update all Tweet objects, marking them as published, if they were created before today. Model.update() accepts keyword arguments where the keys correspond to the model’s field names:

  1. >>> today = datetime.today()
  2. >>> query = Tweet.update(is_published=True).where(Tweet.creation_date < today)
  3. >>> query.execute() # Returns the number of rows that were updated.
  4. 4

For more information, see the documentation on Model.update() and UpdateQuery.

Note

If you would like more information on performing atomic updates (such as incrementing the value of a column), check out the atomic update recipes.

Atomic updates

Peewee allows you to perform atomic updates. Let’s suppose we need to update some counters. The naive approach would be to write something like this:

  1. >>> for stat in Stat.select().where(Stat.url == request.url):
  2. ... stat.counter += 1
  3. ... stat.save()

Do not do this! Not only is this slow, but it is also vulnerable to race conditions if multiple processes are updating the counter at the same time.

Instead, you can update the counters atomically using update():

  1. >>> query = Stat.update(counter=Stat.counter + 1).where(Stat.url == request.url)
  2. >>> query.execute()

You can make these update statements as complex as you like. Let’s give all our employees a bonus equal to their previous bonus plus 10% of their salary:

  1. >>> query = Employee.update(bonus=(Employee.bonus + (Employee.salary * .1)))
  2. >>> query.execute() # Give everyone a bonus!

We can even use a subquery to update the value of a column. Suppose we had a denormalized column on the User model that stored the number of tweets a user had made, and we updated this value periodically. Here is how you might write such a query:

  1. >>> subquery = Tweet.select(fn.COUNT(Tweet.id)).where(Tweet.user == User.id)
  2. >>> update = User.update(num_tweets=subquery)
  3. >>> update.execute()

Deleting records

To delete a single model instance, you can use the Model.delete_instance() shortcut. delete_instance() will delete the given model instance and can optionally delete any dependent objects recursively (by specifying recursive=True).

  1. >>> user = User.get(User.id == 1)
  2. >>> user.delete_instance() # Returns the number of rows deleted.
  3. 1
  4. >>> User.get(User.id == 1)
  5. UserDoesNotExist: instance matching query does not exist:
  6. SQL: SELECT t1."id", t1."username" FROM "user" AS t1 WHERE t1."id" = ?
  7. PARAMS: [1]

To delete an arbitrary set of rows, you can issue a DELETE query. The following will delete all Tweet objects that are over one year old:

  1. >>> query = Tweet.delete().where(Tweet.creation_date < one_year_ago)
  2. >>> query.execute() # Returns the number of rows deleted.
  3. 7

For more information, see the documentation on:

Selecting a single record

You can use the Model.get() method to retrieve a single instance matching the given query.

This method is a shortcut that calls Model.select() with the given query, but limits the result set to a single row. Additionally, if no model matches the given query, a DoesNotExist exception will be raised.

  1. >>> User.get(User.id == 1)
  2. <__main__.User object at 0x25294d0>
  3. >>> User.get(User.id == 1).username
  4. u'Charlie'
  5. >>> User.get(User.username == 'Charlie')
  6. <__main__.User object at 0x2529410>
  7. >>> User.get(User.username == 'nobody')
  8. UserDoesNotExist: instance matching query does not exist:
  9. SQL: SELECT t1."id", t1."username" FROM "user" AS t1 WHERE t1."username" = ?
  10. PARAMS: ['nobody']

For more advanced operations, you can use SelectQuery.get(). The following query retrieves the latest tweet from the user named charlie:

  1. >>> (Tweet
  2. ... .select()
  3. ... .join(User)
  4. ... .where(User.username == 'charlie')
  5. ... .order_by(Tweet.created_date.desc())
  6. ... .get())
  7. <__main__.Tweet object at 0x2623410>

For more information, see the documentation on:

Create or get

Peewee has one helper method for performing “get/create” type operations:

  • Model.get_or_create(), which first attempts to retrieve the matching row. Failing that, a new row will be created.

For “create or get” type logic, typically one would rely on a unique constraint or primary key to prevent the creation of duplicate objects. As an example, let’s say we wish to implement registering a new user account using the example User model. The User model has a unique constraint on the username field, so we will rely on the database’s integrity guarantees to ensure we don’t end up with duplicate usernames:

  1. try:
  2. with db.atomic():
  3. return User.create(username=username)
  4. except peewee.IntegrityError:
  5. # `username` is a unique column, so this username already exists,
  6. # making it safe to call .get().
  7. return User.get(User.username == username)

You can easily encapsulate this type of logic as a classmethod on your own Model classes.

The above example first attempts at creation, then falls back to retrieval, relying on the database to enforce a unique constraint. If you prefer to attempt to retrieve the record first, you can use get_or_create(). This method is implemented along the same lines as the Django function of the same name. You can use the Django-style keyword argument filters to specify your WHERE conditions. The function returns a 2-tuple containing the instance and a boolean value indicating if the object was created.

Here is how you might implement user account creation using get_or_create():

  1. user, created = User.get_or_create(username=username)

Suppose we have a different model Person and would like to get or create a person object. The only conditions we care about when retrieving the Person are their first and last names, but if we end up needing to create a new record, we will also specify their date-of-birth and favorite color:

  1. person, created = Person.get_or_create(
  2. first_name=first_name,
  3. last_name=last_name,
  4. defaults={'dob': dob, 'favorite_color': 'green'})

Any keyword argument passed to get_or_create() will be used in the get() portion of the logic, except for the defaults dictionary, which will be used to populate values on newly-created instances.

For more details check out the documentation for Model.get_or_create().

Selecting multiple records

We can use Model.select() to retrieve rows from the table. When you construct a SELECT query, the database will return any rows that correspond to your query. Peewee allows you to iterate over these rows, as well as use indexing and slicing operations.

In the following example, we will simply call select() and iterate over the return value, which is an instance of SelectQuery. This will return all the rows in the User table:

  1. >>> for user in User.select():
  2. ... print user.username
  3. ...
  4. Charlie
  5. Huey
  6. Peewee

Note

Subsequent iterations of the same query will not hit the database as the results are cached. To disable this behavior (to reduce memory usage), call SelectQuery.iterator() when iterating.

When iterating over a model that contains a foreign key, be careful with the way you access values on related models. Accidentally resolving a foreign key or iterating over a back-reference can cause N+1 query behavior.

When you create a foreign key, such as Tweet.user, you can use the related_name to create a back-reference (User.tweets). Back-references are exposed as SelectQuery instances:

  1. >>> tweet = Tweet.get()
  2. >>> tweet.user # Accessing a foreign key returns the related model.
  3. <tw.User at 0x7f3ceb017f50>
  4. >>> user = User.get()
  5. >>> user.tweets # Accessing a back-reference returns a query.
  6. <SelectQuery> SELECT t1."id", t1."user_id", t1."message", t1."created_date", t1."is_published" FROM "tweet" AS t1 WHERE (t1."user_id" = ?) [1]

You can iterate over the user.tweets back-reference just like any other SelectQuery:

  1. >>> for tweet in user.tweets:
  2. ... print tweet.message
  3. ...
  4. hello world
  5. this is fun
  6. look at this picture of my food

Filtering records

You can filter for particular records using normal python operators. Peewee supports a wide variety of query operators.

  1. >>> user = User.get(User.username == 'Charlie')
  2. >>> for tweet in Tweet.select().where(Tweet.user == user, Tweet.is_published == True):
  3. ... print '%s: %s' % (tweet.user.username, tweet.message)
  4. ...
  5. Charlie: hello world
  6. Charlie: this is fun
  7. >>> for tweet in Tweet.select().where(Tweet.created_date < datetime.datetime(2011, 1, 1)):
  8. ... print tweet.message, tweet.created_date
  9. ...
  10. Really old tweet 2010-01-01 00:00:00

You can also filter across joins:

  1. >>> for tweet in Tweet.select().join(User).where(User.username == 'Charlie'):
  2. ... print tweet.message
  3. hello world
  4. this is fun
  5. look at this picture of my food

If you want to express a complex query, use parentheses and python’s bitwise or and and operators:

  1. >>> Tweet.select().join(User).where(
  2. ... (User.username == 'Charlie') |
  3. ... (User.username == 'Peewee Herman')
  4. ... )

Check out the table of query operations to see what types of queries are possible.

Note

A lot of fun things can go in the where clause of a query, such as:

  • A field expression, e.g. User.username == 'Charlie'
  • A function expression, e.g. fn.Lower(fn.Substr(User.username, 1, 1)) == 'a'
  • A comparison of one column to another, e.g. Employee.salary < (Employee.tenure * 1000) + 40000

You can also nest queries, for example tweets by users whose username starts with “a”:

  1. # get users whose username starts with "a"
  2. a_users = User.select().where(fn.Lower(fn.Substr(User.username, 1, 1)) == 'a')
  3. # the "<<" operator signifies an "IN" query
  4. a_user_tweets = Tweet.select().where(Tweet.user << a_users)

More query examples

Get active users:

  1. User.select().where(User.active == True)

Get users who are either staff or superusers:

  1. User.select().where(
  2. (User.is_staff == True) | (User.is_superuser == True))

Get tweets by user named “charlie”:

  1. Tweet.select().join(User).where(User.username == 'charlie')

Get tweets by staff or superusers (assumes FK relationship):

  1. Tweet.select().join(User).where(
  2. (User.is_staff == True) | (User.is_superuser == True))

Get tweets by staff or superusers using a subquery:

  1. staff_super = User.select(User.id).where(
  2. (User.is_staff == True) | (User.is_superuser == True))
  3. Tweet.select().where(Tweet.user << staff_super)

Sorting records

To return rows in order, use the order_by() method:

  1. >>> for t in Tweet.select().order_by(Tweet.created_date):
  2. ... print t.pub_date
  3. ...
  4. 2010-01-01 00:00:00
  5. 2011-06-07 14:08:48
  6. 2011-06-07 14:12:57
  7. >>> for t in Tweet.select().order_by(Tweet.created_date.desc()):
  8. ... print t.pub_date
  9. ...
  10. 2011-06-07 14:12:57
  11. 2011-06-07 14:08:48
  12. 2010-01-01 00:00:00

You can also use + and - prefix operators to indicate ordering:

  1. # The following queries are equivalent:
  2. Tweet.select().order_by(Tweet.created_date.desc())
  3. Tweet.select().order_by(-Tweet.created_date) # Note the "-" prefix.
  4. # Similarly you can use "+" to indicate ascending order:
  5. User.select().order_by(+User.username)

You can also order across joins. Assuming you want to order tweets by the username of the author, then by created_date:

  1. >>> qry = Tweet.select().join(User).order_by(User.username, Tweet.created_date.desc())
  1. SELECT t1."id", t1."user_id", t1."message", t1."is_published", t1."created_date"
  2. FROM "tweet" AS t1
  3. INNER JOIN "user" AS t2
  4. ON t1."user_id" = t2."id"
  5. ORDER BY t2."username", t1."created_date" DESC

When sorting on a calculated value, you can either include the necessary SQL expressions, or reference the alias assigned to the value. Here are two examples illustrating these methods:

  1. # Let's start with our base query. We want to get all usernames and the number of
  2. # tweets they've made. We wish to sort this list from users with most tweets to
  3. # users with fewest tweets.
  4. query = (User
  5. .select(User.username, fn.COUNT(Tweet.id).alias('num_tweets'))
  6. .join(Tweet, JOIN.LEFT_OUTER)
  7. .group_by(User.username))

You can order using the same COUNT expression used in the select clause. In the example below we are ordering by the COUNT() of tweet ids descending:

  1. query = (User
  2. .select(User.username, fn.COUNT(Tweet.id).alias('num_tweets'))
  3. .join(Tweet, JOIN.LEFT_OUTER)
  4. .group_by(User.username)
  5. .order_by(fn.COUNT(Tweet.id).desc()))

Alternatively, you can reference the alias assigned to the calculated value in the select clause. This method has the benefit of being a bit easier to read. Note that we are not referring to the named alias directly, but are wrapping it using the SQL helper:

  1. query = (User
  2. .select(User.username, fn.COUNT(Tweet.id).alias('num_tweets'))
  3. .join(Tweet, JOIN.LEFT_OUTER)
  4. .group_by(User.username)
  5. .order_by(SQL('num_tweets').desc()))

Getting random records

Occasionally you may want to pull a random record from the database. You can accomplish this by ordering by the random or rand function (depending on your database):

Postgresql and Sqlite use the Random function:

  1. # Pick 5 lucky winners:
  2. LotteryNumber.select().order_by(fn.Random()).limit(5)

MySQL uses Rand:

  1. # Pick 5 lucky winners:
  2. LotterNumber.select().order_by(fn.Rand()).limit(5)

Paginating records

The paginate() method makes it easy to grab a page or records. paginate() takes two parameters, page_number, and items_per_page.

Attention

Page numbers are 1-based, so the first page of results will be page 1.

  1. >>> for tweet in Tweet.select().order_by(Tweet.id).paginate(2, 10):
  2. ... print tweet.message
  3. ...
  4. tweet 10
  5. tweet 11
  6. tweet 12
  7. tweet 13
  8. tweet 14
  9. tweet 15
  10. tweet 16
  11. tweet 17
  12. tweet 18
  13. tweet 19

If you would like more granular control, you can always use limit() and offset().

Counting records

You can count the number of rows in any select query:

  1. >>> Tweet.select().count()
  2. 100
  3. >>> Tweet.select().where(Tweet.id > 50).count()
  4. 50

In some cases it may be necessary to wrap your query and apply a count to the rows of the inner query (such as when using DISTINCT or GROUP BY). Peewee will usually do this automatically, but in some cases you may need to manually call wrapped_count() instead.

Aggregating records

Suppose you have some users and want to get a list of them along with the count of tweets in each. The annotate() method provides a short-hand for creating these types of queries:

  1. query = User.select().annotate(Tweet)

The above query is equivalent to:

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

The resulting query will return User objects with all their normal attributes plus an additional attribute count which will contain the count of tweets for each user. By default it uses an inner join if the foreign key is not nullable, which means users without tweets won’t appear in the list. To remedy this, manually specify the type of join to include users with 0 tweets:

  1. query = (User
  2. .select()
  3. .join(Tweet, JOIN.LEFT_OUTER)
  4. .switch(User)
  5. .annotate(Tweet))

You can also specify a custom aggregator, such as MIN or MAX:

  1. query = (User
  2. .select()
  3. .annotate(
  4. Tweet,
  5. fn.Max(Tweet.created_date).alias('latest_tweet_date')))

Let’s assume you have a tagging application and want to find tags that have a certain number of related objects. For this example we’ll use some different models in a many-to-many configuration:

  1. class Photo(Model):
  2. image = CharField()
  3. class Tag(Model):
  4. name = CharField()
  5. class PhotoTag(Model):
  6. photo = ForeignKeyField(Photo)
  7. tag = ForeignKeyField(Tag)

Now say we want to find tags that have at least 5 photos associated with them:

  1. query = (Tag
  2. .select()
  3. .join(PhotoTag)
  4. .join(Photo)
  5. .group_by(Tag)
  6. .having(fn.Count(Photo.id) > 5))

This query is equivalent to the following SQL:

  1. SELECT t1."id", t1."name"
  2. FROM "tag" AS t1
  3. INNER JOIN "phototag" AS t2 ON t1."id" = t2."tag_id"
  4. INNER JOIN "photo" AS t3 ON t2."photo_id" = t3."id"
  5. GROUP BY t1."id", t1."name"
  6. HAVING Count(t3."id") > 5

Suppose we want to grab the associated count and store it on the tag:

  1. query = (Tag
  2. .select(Tag, fn.Count(Photo.id).alias('count'))
  3. .join(PhotoTag)
  4. .join(Photo)
  5. .group_by(Tag)
  6. .having(fn.Count(Photo.id) > 5))

Retrieving Scalar Values

You can retrieve scalar values by calling Query.scalar(). For instance:

  1. >>> PageView.select(fn.Count(fn.Distinct(PageView.url))).scalar()
  2. 100

You can retrieve multiple scalar values by passing as_tuple=True:

  1. >>> Employee.select(
  2. ... fn.Min(Employee.salary), fn.Max(Employee.salary)
  3. ... ).scalar(as_tuple=True)
  4. (30000, 50000)

SQL Functions, Subqueries and “Raw expressions”

Suppose you need to want to get a list of all users whose username begins with a. There are a couple ways to do this, but one method might be to use some SQL functions like LOWER and SUBSTR. To use arbitrary SQL functions, use the special fn() object to construct queries:

  1. # Select the user's id, username and the first letter of their username, lower-cased
  2. query = User.select(User, fn.Lower(fn.Substr(User.username, 1, 1)).alias('first_letter'))
  3. # Alternatively we could select only users whose username begins with 'a'
  4. a_users = User.select().where(fn.Lower(fn.Substr(User.username, 1, 1)) == 'a')
  5. >>> for user in a_users:
  6. ... print user.username

There are times when you may want to simply pass in some arbitrary sql. You can do this using the special SQL class. One use-case is when referencing an alias:

  1. # We'll query the user table and annotate it with a count of tweets for
  2. # the given user
  3. query = User.select(User, fn.Count(Tweet.id).alias('ct')).join(Tweet).group_by(User)
  4. # Now we will order by the count, which was aliased to "ct"
  5. query = query.order_by(SQL('ct'))

There are two ways to execute hand-crafted SQL statements with peewee:

  1. Database.execute_sql() for executing any type of query
  2. RawQuery for executing SELECT queries and returning model instances.

Example:

  1. db = SqliteDatabase(':memory:')
  2. class Person(Model):
  3. name = CharField()
  4. class Meta:
  5. database = db
  6. # let's pretend we want to do an "upsert", something that SQLite can
  7. # do, but peewee cannot.
  8. for name in ('charlie', 'mickey', 'huey'):
  9. db.execute_sql('REPLACE INTO person (name) VALUES (?)', (name,))
  10. # now let's iterate over the people using our own query.
  11. for person in Person.raw('select * from person'):
  12. print person.name # .raw() will return model instances.

Security and SQL Injection

By default peewee will parameterize queries, so any parameters passed in by the user will be escaped. The only exception to this rule is if you are writing a raw SQL query or are passing in a SQL object which may contain untrusted data. To mitigate this, ensure that any user-defined data is passed in as a query parameter and not part of the actual SQL query:

  1. # Bad!
  2. query = MyModel.raw('SELECT * FROM my_table WHERE data = %s' % (user_data,))
  3. # Good. `user_data` will be treated as a parameter to the query.
  4. query = MyModel.raw('SELECT * FROM my_table WHERE data = %s', user_data)
  5. # Bad!
  6. query = MyModel.select().where(SQL('Some SQL expression %s' % user_data))
  7. # Good. `user_data` will be treated as a parameter.
  8. query = MyModel.select().where(SQL('Some SQL expression %s', user_data))

Note

MySQL and Postgresql use '%s' to denote parameters. SQLite, on the other hand, uses '?'. Be sure to use the character appropriate to your database. You can also find this parameter by checking Database.interpolation.

Window functions

peewee comes with basic support for SQL window functions, which can be created by calling fn.over() and passing in your partitioning or ordering parameters.

  1. # Get the list of employees and the average salary for their dept.
  2. query = (Employee
  3. .select(
  4. Employee.name,
  5. Employee.department,
  6. Employee.salary,
  7. fn.Avg(Employee.salary).over(
  8. partition_by=[Employee.department]))
  9. .order_by(Employee.name))
  10. # Rank employees by salary.
  11. query = (Employee
  12. .select(
  13. Employee.name,
  14. Employee.salary,
  15. fn.rank().over(
  16. order_by=[Employee.salary])))

For general information on window functions, check out the postgresql docs.

Retrieving raw tuples / dictionaries

Sometimes you do not need the overhead of creating model instances and simply want to iterate over the row tuples. To do this, call SelectQuery.tuples() or RawQuery.tuples():

  1. stats = Stat.select(Stat.url, fn.Count(Stat.url)).group_by(Stat.url).tuples()
  2. # iterate over a list of 2-tuples containing the url and count
  3. for stat_url, stat_count in stats:
  4. print stat_url, stat_count

Similarly, you can return the rows from the cursor as dictionaries using SelectQuery.dicts() or RawQuery.dicts():

  1. stats = Stat.select(Stat.url, fn.Count(Stat.url).alias('ct')).group_by(Stat.url).dicts()
  2. # iterate over a list of 2-tuples containing the url and count
  3. for stat in stats:
  4. print stat['url'], stat['ct']

Returning Clause

PostgresqlDatabase supports a RETURNING clause on UPDATE, INSERT and DELETE queries. Specifying a RETURNING clause allows you to iterate over the rows accessed by the query.

For example, let’s say you have an UpdateQuery that deactivates all user accounts whose registration has expired. After deactivating them, you want to send each user an email letting them know their account was deactivated. Rather than writing two queries, a SELECT and an UPDATE, you can do this in a single UPDATE query with a RETURNING clause:

  1. query = (User
  2. .update(is_active=False)
  3. .where(User.registration_expired == True)
  4. .returning(User))
  5. # Send an email to every user that was deactivated.
  6. for deactivate_user in query.execute():
  7. send_deactivation_email(deactivated_user)

The RETURNING clause is also available on InsertQuery and DeleteQuery. When used with INSERT, the newly-created rows will be returned. When used with DELETE, the deleted rows will be returned.

The only limitation of the RETURNING clause is that it can only consist of columns from tables listed in the query’s FROM clause. To select all columns from a particular table, you can simply pass in the Model class.

For more information, see:

Query operators

The following types of comparisons are supported by peewee:

ComparisonMeaning
==x equals y
<x is less than y
<=x is less than or equal to y
>x is greater than y
>=x is greater than or equal to y
!=x is not equal to y
<<x IN y, where y is a list or query
>>x IS y, where y is None/NULL
%x LIKE y where y may contain wildcards
**x ILIKE y where y may contain wildcards
~Negation

Because I ran out of operators to override, there are some additional query operations available as methods:

MethodMeaning
.contains(substr)Wild-card search for substring.
.startswith(prefix)Search for values beginning with prefix.
.endswith(suffix)Search for values ending with suffix.
.between(low, high)Search for values between low and high.
.regexp(exp)Regular expression match.
.binand(value)Binary AND.
.bin_or(value)Binary OR.
.in(value)IN lookup (identical to <<).
.not_in(value)NOT IN lookup.
.is_null(is_null)IS NULL or IS NOT NULL. Accepts boolean param.
.concat(other)Concatenate two strings using ||.

To combine clauses using logical operators, use:

OperatorMeaningExample
&AND(User.is_active == True) & (User.is_admin == True)
| (pipe)OR(User.is_admin) | (User.is_superuser)
~NOT (unary negation)~(User.username << [‘foo’, ‘bar’, ‘baz’])

Here is how you might use some of these query operators:

  1. # Find the user whose username is "charlie".
  2. User.select().where(User.username == 'charlie')
  3. # Find the users whose username is in [charlie, huey, mickey]
  4. User.select().where(User.username << ['charlie', 'huey', 'mickey'])
  5. Employee.select().where(Employee.salary.between(50000, 60000))
  6. Employee.select().where(Employee.name.startswith('C'))
  7. Blog.select().where(Blog.title.contains(search_string))

Here is how you might combine expressions. Comparisons can be arbitrarily complex.

Note

Note that the actual comparisons are wrapped in parentheses. Python’s operator precedence necessitates that comparisons be wrapped in parentheses.

  1. # Find any users who are active administrations.
  2. User.select().where(
  3. (User.is_admin == True) &
  4. (User.is_active == True))
  5. # Find any users who are either administrators or super-users.
  6. User.select().where(
  7. (User.is_admin == True) |
  8. (User.is_superuser == True))
  9. # Find any Tweets by users who are not admins (NOT IN).
  10. admins = User.select().where(User.is_admin == True)
  11. non_admin_tweets = Tweet.select().where(
  12. ~(Tweet.user << admins))
  13. # Find any users who are not my friends (strangers).
  14. friends = User.select().where(
  15. User.username << ['charlie', 'huey', 'mickey'])
  16. strangers = User.select().where(~(User.id << friends))

Warning

Although you may be tempted to use python’s in, and, or and not operators in your query expressions, these will not work. The return value of an in expression is always coerced to a boolean value. Similarly, and, or and not all treat their arguments as boolean values and cannot be overloaded.

So just remember:

  • Use << instead of in
  • Use & instead of and
  • Use | instead of or
  • Use ~ instead of not
  • Don’t forget to wrap your comparisons in parentheses when using logical operators.

For more examples, see the Expressions section.

Note

LIKE and ILIKE with SQLite

Because SQLite’s LIKE operation is case-insensitive by default, peewee will use the SQLite GLOB operation for case-sensitive searches. The glob operation uses asterisks for wildcards as opposed to the usual percent-sign. If you are using SQLite and want case-sensitive partial string matching, remember to use asterisks for the wildcard.

Three valued logic

Because of the way SQL handles NULL, there are some special operations available for expressing:

  • IS NULL
  • IS NOT NULL
  • IN
  • NOT IN

While it would be possible to use the IS NULL and IN operators with the negation operator (~), sometimes to get the correct semantics you will need to explicitly use IS NOT NULL and NOT IN.

The simplest way to use IS NULL and IN is to use the operator overloads:

  1. # Get all User objects whose last login is NULL.
  2. User.select().where(User.last_login >> None)
  3. # Get users whose username is in the given list.
  4. usernames = ['charlie', 'huey', 'mickey']
  5. User.select().where(User.username << usernames)

If you don’t like operator overloads, you can call the Field methods instead:

  1. # Get all User objects whose last login is NULL.
  2. User.select().where(User.last_login.is_null(True))
  3. # Get users whose username is in the given list.
  4. usernames = ['charlie', 'huey', 'mickey']
  5. User.select().where(User.username.in_(usernames))

To negate the above queries, you can use unary negation, but for the correct semantics you may need to use the special IS NOT and NOT IN operators:

  1. # Get all User objects whose last login is *NOT* NULL.
  2. User.select().where(User.last_login.is_null(False))
  3. # Using unary negation instead.
  4. User.select().where(~(User.last_login >> None))
  5. # Get users whose username is *NOT* in the given list.
  6. usernames = ['charlie', 'huey', 'mickey']
  7. User.select().where(User.username.not_in(usernames))
  8. # Using unary negation instead.
  9. usernames = ['charlie', 'huey', 'mickey']
  10. User.select().where(~(User.username << usernames))

Adding user-defined operators

Because I ran out of python operators to overload, there are some missing operators in peewee, for instance modulo. If you find that you need to support an operator that is not in the table above, it is very easy to add your own.

Here is how you might add support for modulo in SQLite:

  1. from peewee import *
  2. from peewee import Expression # the building block for expressions
  3. OP['MOD'] = 'mod'
  4. def mod(lhs, rhs):
  5. return Expression(lhs, OP.MOD, rhs)
  6. SqliteDatabase.register_ops({OP.MOD: '%'})

Now you can use these custom operators to build richer queries:

  1. # Users with even ids.
  2. User.select().where(mod(User.id, 2) == 0)

For more examples check out the source to the playhouse.postgresql_ext module, as it contains numerous operators specific to postgresql’s hstore.

Expressions

Peewee is designed to provide a simple, expressive, and pythonic way of constructing SQL queries. This section will provide a quick overview of some common types of expressions.

There are two primary types of objects that can be composed to create expressions:

  • Field instances
  • SQL aggregations and functions using fn

We will assume a simple “User” model with fields for username and other things. It looks like this:

  1. class User(Model):
  2. username = CharField()
  3. is_admin = BooleanField()
  4. is_active = BooleanField()
  5. last_login = DateTimeField()
  6. login_count = IntegerField()
  7. failed_logins = IntegerField()

Comparisons use the Query operators:

  1. # username is equal to 'charlie'
  2. User.username == 'charlie'
  3. # user has logged in less than 5 times
  4. User.login_count < 5

Comparisons can be combined using bitwise and and or. Operator precedence is controlled by python and comparisons can be nested to an arbitrary depth:

  1. # User is both and admin and has logged in today
  2. (User.is_admin == True) & (User.last_login >= today)
  3. # User's username is either charlie or charles
  4. (User.username == 'charlie') | (User.username == 'charles')

Comparisons can be used with functions as well:

  1. # user's username starts with a 'g' or a 'G':
  2. fn.Lower(fn.Substr(User.username, 1, 1)) == 'g'

We can do some fairly interesting things, as expressions can be compared against other expressions. Expressions also support arithmetic operations:

  1. # users who entered the incorrect more than half the time and have logged
  2. # in at least 10 times
  3. (User.failed_logins > (User.login_count * .5)) & (User.login_count > 10)

Expressions allow us to do atomic updates:

  1. # when a user logs in we want to increment their login count:
  2. User.update(login_count=User.login_count + 1).where(User.id == user_id)

Expressions can be used in all parts of a query, so experiment!

Foreign Keys

Foreign keys are created using a special field class ForeignKeyField. Each foreign key also creates a back-reference on the related model using the specified related_name.

Traversing foreign keys

Referring back to the User and Tweet models, note that there is a ForeignKeyField from Tweet to User. The foreign key can be traversed, allowing you access to the associated user instance:

  1. >>> tweet.user.username
  2. 'charlie'

Note

Unless the User model was explicitly selected when retrieving the Tweet, an additional query will be required to load the User data. To learn how to avoid the extra query, see the N+1 query documentation.

The reverse is also true, and we can iterate over the tweets associated with a given User instance:

  1. >>> for tweet in user.tweets:
  2. ... print tweet.message
  3. ...
  4. http://www.youtube.com/watch?v=xdhLQCYQ-nQ

Under the hood, the tweets attribute is just a SelectQuery with the WHERE clause pre-populated to point to the given User instance:

  1. >>> user.tweets
  2. <class 'twx.Tweet'> SELECT t1."id", t1."user_id", t1."message", ...

Joining tables

Use the join() method to JOIN additional tables. When a foreign key exists between the source model and the join model, you do not need to specify any additional parameters:

  1. >>> my_tweets = Tweet.select().join(User).where(User.username == 'charlie')

By default peewee will use an INNER join, but you can use LEFT OUTER, RIGHT OUTER, FULL, or CROSS joins as well:

  1. users = (User
  2. .select(User, fn.Count(Tweet.id).alias('num_tweets'))
  3. .join(Tweet, JOIN.LEFT_OUTER)
  4. .group_by(User)
  5. .order_by(fn.Count(Tweet.id).desc()))
  6. for user in users:
  7. print user.username, 'has created', user.num_tweets, 'tweet(s).'

Multiple Foreign Keys to the Same Model

When there are multiple foreign keys to the same model, it is good practice to explicitly specify which field you are joining on.

Referring back to the example app’s models, consider the Relationship model, which is used to denote when one user follows another. Here is the model definition:

  1. class Relationship(BaseModel):
  2. from_user = ForeignKeyField(User, related_name='relationships')
  3. to_user = ForeignKeyField(User, related_name='related_to')
  4. class Meta:
  5. indexes = (
  6. # Specify a unique multi-column index on from/to-user.
  7. (('from_user', 'to_user'), True),
  8. )

Since there are two foreign keys to User, we should always specify which field we are using in a join.

For example, to determine which users I am following, I would write:

  1. (User
  2. .select()
  3. .join(Relationship, on=Relationship.to_user)
  4. .where(Relationship.from_user == charlie))

On the other hand, if I wanted to determine which users are following me, I would instead join on the from_user column and filter on the relationship’s to_user:

  1. (User
  2. .select()
  3. .join(Relationship, on=Relationship.from_user)
  4. .where(Relationship.to_user == charlie))

Joining on arbitrary fields

If a foreign key does not exist between two tables you can still perform a join, but you must manually specify the join predicate.

In the following example, there is no explicit foreign-key between User and ActivityLog, but there is an implied relationship between the ActivityLog.object_id field and User.id. Rather than joining on a specific Field, we will join using an Expression.

  1. user_log = (User
  2. .select(User, ActivityLog)
  3. .join(
  4. ActivityLog,
  5. on=(User.id == ActivityLog.object_id).alias('log'))
  6. .where(
  7. (ActivityLog.activity_type == 'user_activity') &
  8. (User.username == 'charlie')))
  9. for user in user_log:
  10. print user.username, user.log.description
  11. #### Print something like ####
  12. charlie logged in
  13. charlie posted a tweet
  14. charlie retweeted
  15. charlie posted a tweet
  16. charlie logged out

Note

By specifying an alias on the join condition, you can control the attribute peewee will assign the joined instance to. In the previous example, we used the following join:

  1. (User.id == ActivityLog.object_id).alias('log')

Then when iterating over the query, we were able to directly access the joined ActivityLog without incurring an additional query:

  1. for user in user_log:
  2. print user.username, user.log.description

Joining on Multiple Tables

When calling join(), peewee will use the last joined table as the source table. For example:

  1. User.select().join(Tweet).join(Comment)

This query will result in a join from User to Tweet, and another join from Tweet to Comment.

If you would like to join the same table twice, use the switch() method:

  1. # Join the Artist table on both `Ablum` and `Genre`.
  2. Artist.select().join(Album).switch(Artist).join(Genre)

Implementing Many to Many

Peewee does not provide a field for many to many relationships the way that django does – this is because the field really is hiding an intermediary table. To implement many-to-many with peewee, you will therefore create the intermediary table yourself and query through it:

  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, let’s say we want to find students who are enrolled in math class:

  1. query = (Student
  2. .select()
  3. .join(StudentCourse)
  4. .join(Course)
  5. .where(Course.name == 'math'))
  6. for student in query:
  7. print student.name

To query what classes a given student is enrolled in:

  1. courses = (Course
  2. .select()
  3. .join(StudentCourse)
  4. .join(Student)
  5. .where(Student.name == 'da vinci'))
  6. for course in courses:
  7. print course.name

To efficiently iterate over a many-to-many relation, i.e., list all students and their respective courses, we will query the through model StudentCourse and precompute the Student and Course:

  1. query = (StudentCourse
  2. .select(StudentCourse, Student, Course)
  3. .join(Course)
  4. .switch(StudentCourse)
  5. .join(Student)
  6. .order_by(Student.name))

To print a list of students and their courses you might do the following:

  1. last = None
  2. for student_course in query:
  3. student = student_course.student
  4. if student != last:
  5. last = student
  6. print 'Student: %s' % student.name
  7. print ' - %s' % student_course.course.name

Since we selected all fields from Student and Course in the select clause of the query, these foreign key traversals are “free” and we’ve done the whole iteration with just 1 query.

ManyToManyField

The ManyToManyField provides a field-like API over many-to-many fields. For all but the simplest many-to-many situations, you’re better off using the standard peewee APIs. But, if your models are very simple and your querying needs are not very complex, you can get a big boost by using ManyToManyField. Check out the Fields extension module for details.

Modeling students and courses using ManyToManyField:

  1. from peewee import *
  2. from playhouse.fields import ManyToManyField
  3. db = SqliteDatabase('school.db')
  4. class BaseModel(Model):
  5. class Meta:
  6. database = db
  7. class Student(BaseModel):
  8. name = CharField()
  9. class Course(BaseModel):
  10. name = CharField()
  11. students = ManyToManyField(Student, related_name='courses')
  12. StudentCourse = Course.students.get_through_model()
  13. db.create_tables([
  14. Student,
  15. Course,
  16. StudentCourse])
  17. # Get all classes that "huey" is enrolled in:
  18. huey = Student.get(Student.name == 'Huey')
  19. for course in huey.courses.order_by(Course.name):
  20. print course.name
  21. # Get all students in "English 101":
  22. engl_101 = Course.get(Course.name == 'English 101')
  23. for student in engl_101.students:
  24. print student.name
  25. # When adding objects to a many-to-many relationship, we can pass
  26. # in either a single model instance, a list of models, or even a
  27. # query of models:
  28. huey.courses.add(Course.select().where(Course.name.contains('English')))
  29. engl_101.students.add(Student.get(Student.name == 'Mickey'))
  30. engl_101.students.add([
  31. Student.get(Student.name == 'Charlie'),
  32. Student.get(Student.name == 'Zaizee')])
  33. # The same rules apply for removing items from a many-to-many:
  34. huey.courses.remove(Course.select().where(Course.name.startswith('CS')))
  35. engl_101.students.remove(huey)
  36. # Calling .clear() will remove all associated objects:
  37. cs_150.students.clear()

For more examples, see:

Self-joins

Peewee supports several methods for constructing queries containing a self-join.

Using model aliases

To join on the same model (table) twice, it is necessary to create a model alias to represent the second instance of the table in a query. Consider the following model:

  1. class Category(Model):
  2. name = CharField()
  3. parent = ForeignKeyField('self', related_name='children')

What if we wanted to query all categories whose parent category is Electronics. One way would be to perform a self-join:

  1. Parent = Category.alias()
  2. query = (Category
  3. .select()
  4. .join(Parent, on=(Category.parent == Parent.id))
  5. .where(Parent.name == 'Electronics'))

When performing a join that uses a ModelAlias, it is necessary to specify the join condition using the on keyword argument. In this case we are joining the category with its parent category.

Using subqueries

Another less common approach involves the use of subqueries. Here is another way we might construct a query to get all the categories whose parent category is Electronics using a subquery:

  1. join_query = Category.select().where(Category.name == 'Electronics')
  2. # Subqueries used as JOINs need to have an alias.
  3. join_query = join_query.alias('jq')
  4. query = (Category
  5. .select()
  6. .join(join_query, on=(Category.parent == join_query.c.id)))

This will generate the following SQL query:

  1. SELECT t1."id", t1."name", t1."parent_id"
  2. FROM "category" AS t1
  3. INNER JOIN (
  4. SELECT t3."id"
  5. FROM "category" AS t3
  6. WHERE (t3."name" = ?)
  7. ) AS jq ON (t1."parent_id" = "jq"."id"

To access the id value from the subquery, we use the .c magic lookup which will generate the appropriate SQL expression:

  1. Category.parent == join_query.c.id
  2. # Becomes: (t1."parent_id" = "jq"."id")

Performance Techniques

This section outlines some techniques for improving performance when using peewee.

Avoiding N+1 queries

The term N+1 queries refers to a situation where an application performs a query, then for each row of the result set, the application performs at least one other query (another way to conceptualize this is as a nested loop). In many cases, these n queries can be avoided through the use of a SQL join or subquery. The database itself may do a nested loop, but it will usually be more performant than doing n queries in your application code, which involves latency communicating with the database and may not take advantage of indices or other optimizations employed by the database when joining or executing a subquery.

Peewee provides several APIs for mitigating N+1 query behavior. Recollecting the models used throughout this document, User and Tweet, this section will try to outline some common N+1 scenarios, and how peewee can help you avoid them.

Note

In some cases, N+1 queries will not result in a significant or measurable performance hit. It all depends on the data you are querying, the database you are using, and the latency involved in executing queries and retrieving results. As always when making optimizations, profile before and after to ensure the changes do what you expect them to.

List recent tweets

The twitter timeline displays a list of tweets from multiple users. In addition to the tweet’s content, the username of the tweet’s author is also displayed. The N+1 scenario here would be:

  1. Fetch the 10 most recent tweets.
  2. For each tweet, select the author (10 queries).

By selecting both tables and using a join, peewee makes it possible to accomplish this in a single query:

  1. query = (Tweet
  2. .select(Tweet, User) # Note that we are selecting both models.
  3. .join(User) # Use an INNER join because every tweet has an author.
  4. .order_by(Tweet.id.desc()) # Get the most recent tweets.
  5. .limit(10))
  6. for tweet in query:
  7. print tweet.user.username, '-', tweet.message

Without the join, accessing tweet.user.username would trigger a query to resolve the foreign key tweet.user and retrieve the associated user. But since we have selected and joined on User, peewee will automatically resolve the foreign-key for us.

List users and all their tweets

Let’s say you want to build a page that shows several users and all of their tweets. The N+1 scenario would be:

  1. Fetch some users.
  2. For each user, fetch their tweets.

This situation is similar to the previous example, but there is one important difference: when we selected tweets, they only have a single associated user, so we could directly assign the foreign key. The reverse is not true, however, as one user may have any number of tweets (or none at all).

Peewee provides two approaches to avoiding O(n) queries in this situation. We can either:

  • Fetch users first, then fetch all the tweets associated with those users. Once peewee has the big list of tweets, it will assign them out, matching them with the appropriate user. This method is usually faster but will involve a query for each table being selected.
  • Fetch both users and tweets in a single query. User data will be duplicated, so peewee will de-dupe it and aggregate the tweets as it iterates through the result set. This method involves a lot of data being transferred over the wire and a lot of logic in Python to de-duplicate rows.

Each solution has its place and, depending on the size and shape of the data you are querying, one may be more performant than the other.

Using prefetch

peewee supports pre-fetching related data using sub-queries. This method requires the use of a special API, prefetch(). Pre-fetch, as its name indicates, will eagerly load the appropriate tweets for the given users using subqueries. This means instead of O(n) queries for n rows, we will do O(k) queries for k tables.

Here is an example of how we might fetch several users and any tweets they created within the past week.

  1. week_ago = datetime.date.today() - datetime.timedelta(days=7)
  2. users = User.select()
  3. tweets = (Tweet
  4. .select()
  5. .where(
  6. (Tweet.is_published == True) &
  7. (Tweet.created_date >= week_ago)))
  8. # This will perform two queries.
  9. users_with_tweets = prefetch(users, tweets)
  10. for user in users_with_tweets:
  11. print user.username
  12. for tweet in user.tweets_prefetch:
  13. print ' ', tweet.message

Note

Note that neither the User query, nor the Tweet query contained a JOIN clause. When using prefetch() you do not need to specify the join.

prefetch() can be used to query an arbitrary number of tables. Check the API documentation for more examples.

Some things to consider when using prefetch():

  • Foreign keys must exist between the models being prefetched.
  • In general it is more performant than aggregate_rows().
  • Typically a lot less data is transferred over the wire since data is not duplicated.
  • There is less Python overhead since we don’t have to de-dupe things.
  • LIMIT works as you’d expect on the outer-most query, but may be difficult to implement correctly if trying to limit the size of the sub-selects.

Using aggregate_rows

The aggregate_rows() approach selects all data in one go and de-dupes things in-memory. Like prefetch(), it can work with arbitrarily complex queries. To use this feature We will use a special flag, aggregate_rows(), when creating our query. This method tells peewee to de-duplicate any rows that, due to the structure of the JOINs, may be duplicated.

Warning

Because there is a lot of computation involved in de-duping data, it is possible that for some queries aggregate_rows() will be significantly less performant than using prefetch() (described in the previous section) or even issuing O(n) simple queries! Profile your code if you’re not sure.

  1. query = (User
  2. .select(User, Tweet) # As in the previous example, we select both tables.
  3. .join(Tweet, JOIN.LEFT_OUTER)
  4. .order_by(User.username) # We need to specify an ordering here.
  5. .aggregate_rows()) # Tell peewee to de-dupe and aggregate results.
  6. for user in query:
  7. print user.username
  8. for tweet in user.tweets:
  9. print ' ', tweet.message

Ordinarily, user.tweets would be a SelectQuery and iterating over it would trigger an additional query. By using aggregate_rows(), though, user.tweets is a Python list and no additional query occurs.

Note

We used a LEFT OUTER join to ensure that users with zero tweets would also be included in the result set.

Below is an example of how we might fetch several users and any tweets they created within the past week. Because we are filtering the tweets and the user may not have any tweets, we need our WHERE clause to allow NULL tweet IDs.

  1. week_ago = datetime.date.today() - datetime.timedelta(days=7)
  2. query = (User
  3. .select(User, Tweet)
  4. .join(Tweet, JOIN.LEFT_OUTER)
  5. .where(
  6. (Tweet.id >> None) | (
  7. (Tweet.is_published == True) &
  8. (Tweet.created_date >= week_ago)))
  9. .order_by(User.username, Tweet.created_date.desc())
  10. .aggregate_rows())
  11. for user in query:
  12. print user.username
  13. for tweet in user.tweets:
  14. print ' ', tweet.message

Some things to consider when using aggregate_rows():

  • You must specify an ordering for each table that is joined on so the rows can be aggregated correctly, sort of similar to itertools.groupby.
  • Do not mix calls to aggregate_rows() with LIMIT or OFFSET clauses, or with get() (which applies a LIMIT 1 SQL clause). Since the aggregate result set may contain more than one item due to rows being duplicated, limits can lead to incorrect behavior. Imagine you have three users, each of whom has 10 tweets. If you run a query with a LIMIT 5, then you will only receive the first user and their first 5 tweets.
  • In general the Python overhead of de-duplicating data can make this method less performant than prefetch(), and sometimes even less performan than simply issuing O(n) simple queries! When in doubt profile.
  • Because every column from every table is included in each row tuple returned by the cursor, this approach can use a lot more bandwidth than prefetch().

Iterating over lots of rows

By default peewee will cache the rows returned when iterating of a SelectQuery. This is an optimization to allow multiple iterations as well as indexing and slicing without causing additional queries. This caching can be problematic, however, when you plan to iterate over a large number of rows.

To reduce the amount of memory used by peewee when iterating over a query, use the iterator() method. This method allows you to iterate without caching each model returned, using much less memory when iterating over large result sets.

  1. # Let's assume we've got 10 million stat objects to dump to a csv file.
  2. stats = Stat.select()
  3. # Our imaginary serializer class
  4. serializer = CSVSerializer()
  5. # Loop over all the stats and serialize.
  6. for stat in stats.iterator():
  7. serializer.serialize_object(stat)

For simple queries you can see further speed improvements by using the naive() method. This method speeds up the construction of peewee model instances from raw cursor data. See the naive() documentation for more details on this optimization.

  1. for stat in stats.naive().iterator():
  2. serializer.serialize_object(stat)

You can also see performance improvements by using the dicts() and tuples() methods.

When iterating over a large number of rows that contain columns from multiple tables, peewee will reconstruct the model graph for each row returned. This operation can be slow for complex graphs. To speed up model creation, you can:

  • Call naive(), which will not construct a graph and simply patch all attributes from the row directly onto a model instance.
  • Use dicts() or tuples().

Speeding up Bulk Inserts

See the Bulk inserts section for details on speeding up bulk insert operations.