Query Builder

Peewee’s high-level Model and Field APIs are built upon lower-level Table and Column counterparts. While these lower-level APIs are not documented in as much detail as their high-level counterparts, this document will present an overview with examples that should hopefully allow you to experiment.

We’ll use the following schema:

  1. CREATE TABLE "person" (
  2. "id" INTEGER NOT NULL PRIMARY KEY,
  3. "first" TEXT NOT NULL,
  4. "last" TEXT NOT NULL);
  5. CREATE TABLE "note" (
  6. "id" INTEGER NOT NULL PRIMARY KEY,
  7. "person_id" INTEGER NOT NULL,
  8. "content" TEXT NOT NULL,
  9. "timestamp" DATETIME NOT NULL,
  10. FOREIGN KEY ("person_id") REFERENCES "person" ("id"));
  11. CREATE TABLE "reminder" (
  12. "id" INTEGER NOT NULL PRIMARY KEY,
  13. "note_id" INTEGER NOT NULL,
  14. "alarm" DATETIME NOT NULL,
  15. FOREIGN KEY ("note_id") REFERENCES "note" ("id"));

Declaring tables

There are two ways we can declare Table objects for working with these tables:

  1. # Explicitly declare columns
  2. Person = Table('person', ('id', 'first', 'last'))
  3. Note = Table('note', ('id', 'person_id', 'content', 'timestamp'))
  4. # Do not declare columns, they will be accessed using magic ".c" attribute
  5. Reminder = Table('reminder')

Typically we will want to bind() our tables to a database. This saves us having to pass the database explicitly every time we wish to execute a query on the table:

  1. db = SqliteDatabase('my_app.db')
  2. Person = Person.bind(db)
  3. Note = Note.bind(db)
  4. Reminder = Reminder.bind(db)

Select queries

To select the first three notes and print their content, we can write:

  1. query = Note.select().order_by(Note.timestamp).limit(3)
  2. for note_dict in query:
  3. print(note_dict['content'])

Note

By default, rows will be returned as dictionaries. You can use the tuples(), namedtuples() or objects() methods to specify a different container for the row data, if you wish.

Because we didn’t specify any columns, all the columns we defined in the note’s Table constructor will be selected. This won’t work for Reminder, as we didn’t specify any columns at all.

To select all notes published in 2018 along with the name of the creator, we will use join(). We’ll also request that rows be returned as namedtuple objects:

  1. query = (Note
  2. .select(Note.content, Note.timestamp, Person.first, Person.last)
  3. .join(Person, on=(Note.person_id == Person.id))
  4. .where(Note.timestamp >= datetime.date(2018, 1, 1))
  5. .order_by(Note.timestamp)
  6. .namedtuples())
  7. for row in query:
  8. print(row.timestamp, '-', row.content, '-', row.first, row.last)

Let’s query for the most prolific people, that is, get the people who have created the most notes. This introduces calling a SQL function (COUNT), which is accomplished using the fn object:

  1. name = Person.first.concat(' ').concat(Person.last)
  2. query = (Person
  3. .select(name.alias('name'), fn.COUNT(Note.id).alias('count'))
  4. .join(Note, JOIN.LEFT_OUTER, on=(Note.person_id == Person.id))
  5. .group_by(name)
  6. .order_by(fn.COUNT(Note.id).desc()))
  7. for row in query:
  8. print(row['name'], row['count'])

There are a couple things to note in the above query:

  • We store an expression in a variable (name), then use it in the query.
  • We call SQL functions using fn.<function>(...) passing arguments as if it were a normal Python function.
  • The alias() method is used to specify the name used for a column or calculation.

As a more complex example, we’ll generate a list of all people and the contents and timestamp of their most recently-published note. To do this, we will end up using the Note table twice in different contexts within the same query, which will require us to use a table alias.

  1. # Start with the query that calculates the timestamp of the most recent
  2. # note for each person.
  3. NA = Note.alias('na')
  4. max_note = (NA
  5. .select(NA.person_id, fn.MAX(NA.timestamp).alias('max_ts'))
  6. .group_by(NA.person_id)
  7. .alias('max_note'))
  8. # Now we'll select from the note table, joining on both the subquery and
  9. # on the person table to construct the result set.
  10. query = (Note
  11. .select(Note.content, Note.timestamp, Person.first, Person.last)
  12. .join(max_note, on=((max_note.c.person_id == Note.person_id) &
  13. (max_note.c.max_ts == Note.timestamp)))
  14. .join(Person, on=(Note.person_id == Person.id))
  15. .order_by(Person.first, Person.last))
  16. for row in query.namedtuples():
  17. print(row.first, row.last, ':', row.timestamp, '-', row.content)

In the join predicate for the join on the max_note subquery, we can reference columns in the subquery using the magical “.c” attribute. So, max_note.c.max_ts is translated into “the max_ts column value from the max_note subquery”.

We can also use the “.c” magic attribute to access columns on tables that do not explicitly define their columns, like we did with the Reminder table. Here’s a simple query to get all reminders for today, along with their associated note content:

  1. today = datetime.date.today()
  2. tomorrow = today + datetime.timedelta(days=1)
  3. query = (Reminder
  4. .select(Reminder.c.alarm, Note.content)
  5. .join(Note, on=(Reminder.c.note_id == Note.id))
  6. .where(Reminder.c.alarm.between(today, tomorrow))
  7. .order_by(Reminder.c.alarm))
  8. for row in query:
  9. print(row['alarm'], row['content'])

Note

The “.c” attribute will not work on tables that explicitly define their columns, to prevent confusion.

Insert queries

Inserting data is straightforward. We can specify data to insert() in two different ways (in both cases, the ID of the new row is returned):

  1. # Using keyword arguments:
  2. zaizee_id = Person.insert(first='zaizee', last='cat').execute()
  3. # Using column: value mappings:
  4. Note.insert({
  5. Note.person_id: zaizee_id,
  6. Note.content: 'meeeeowwww',
  7. Note.timestamp: datetime.datetime.now()}).execute()

It is easy to bulk-insert data, just pass in either:

  • A list of dictionaries (all must have the same keys/columns).
  • A list of tuples, if the columns are specified explicitly.

Examples:

  1. people = [
  2. {'first': 'Bob', 'last': 'Foo'},
  3. {'first': 'Herb', 'last': 'Bar'},
  4. {'first': 'Nuggie', 'last': 'Bar'}]
  5. # Inserting multiple rows returns the ID of the last-inserted row.
  6. last_id = Person.insert(people).execute()
  7. # We can also specify row tuples, so long as we tell Peewee which
  8. # columns the tuple values correspond to:
  9. people = [
  10. ('Bob', 'Foo'),
  11. ('Herb', 'Bar'),
  12. ('Nuggie', 'Bar')]
  13. Person.insert(people, columns=[Person.first, Person.last]).execute()

Update queries

update() queries accept either keyword arguments or a dictionary mapping column to value, just like insert().

Examples:

  1. # "Bob" changed his last name from "Foo" to "Baze".
  2. nrows = (Person
  3. .update(last='Baze')
  4. .where((Person.first == 'Bob') &
  5. (Person.last == 'Foo'))
  6. .execute())
  7. # Use dictionary mapping column to value.
  8. nrows = (Person
  9. .update({Person.last: 'Baze'})
  10. .where((Person.first == 'Bob') &
  11. (Person.last == 'Foo'))
  12. .execute())

You can also use expressions as the value to perform an atomic update. Imagine we have a PageView table and we need to atomically increment the page-view count for some URL:

  1. # Do an atomic update:
  2. (PageView
  3. .update({PageView.count: PageView.count + 1})
  4. .where(PageView.url == some_url)
  5. .execute())

Delete queries

delete() queries are simplest of all, as they do not accept any arguments:

  1. # Delete all notes created before 2018, returning number deleted.
  2. n = Note.delete().where(Note.timestamp < datetime.date(2018, 1, 1)).execute()

Because DELETE (and UPDATE) queries do not support joins, we can use subqueries to delete rows based on values in related tables. For example, here is how you would delete all notes by anyone whose last name is “Foo”:

  1. # Get the id of all people whose last name is "Foo".
  2. foo_people = Person.select(Person.id).where(Person.last == 'Foo')
  3. # Delete all notes by any person whose ID is in the previous query.
  4. Note.delete().where(Note.person_id.in_(foo_people)).execute()

Query Objects

One of the fundamental limitations of the abstractions provided by Peewee 2.x was the absence of a class that represented a structured query with no relation to a given model class.

An example of this might be computing aggregate values over a subquery. For example, the count() method, which returns the count of rows in an arbitrary query, is implemented by wrapping the query:

  1. SELECT COUNT(1) FROM (...)

To accomplish this with Peewee, the implementation is written in this way:

  1. def count(query):
  2. # Select([source1, ... sourcen], [column1, ...columnn])
  3. wrapped = Select(from_list=[query], columns=[fn.COUNT(SQL('1'))])
  4. curs = wrapped.tuples().execute(db)
  5. return curs[0][0] # Return first column from first row of result.

We can actually express this more concisely using the scalar() method, which is suitable for returning values from aggregate queries:

  1. def count(query):
  2. wrapped = Select(from_list=[query], columns=[fn.COUNT(SQL('1'))])
  3. return wrapped.scalar(db)

The Query Examples document has a more complex example, in which we write a query for a facility with the highest number of available slots booked:

The SQL we wish to express is:

  1. SELECT facid, total FROM (
  2. SELECT facid, SUM(slots) AS total,
  3. rank() OVER (order by SUM(slots) DESC) AS rank
  4. FROM bookings
  5. GROUP BY facid
  6. ) AS ranked
  7. WHERE rank = 1

We can express this fairly elegantly by using a plain Select for the outer query:

  1. # Store rank expression in variable for readability.
  2. rank_expr = fn.rank().over(order_by=[fn.SUM(Booking.slots).desc()])
  3. subq = (Booking
  4. .select(Booking.facility, fn.SUM(Booking.slots).alias('total'),
  5. rank_expr.alias('rank'))
  6. .group_by(Booking.facility))
  7. # Use a plain "Select" to create outer query.
  8. query = (Select(columns=[subq.c.facid, subq.c.total])
  9. .from_(subq)
  10. .where(subq.c.rank == 1)
  11. .tuples())
  12. # Iterate over the resulting facility ID(s) and total(s):
  13. for facid, total in query.execute(db):
  14. print(facid, total)

For another example, let’s create a recursive common table expression to calculate the first 10 fibonacci numbers:

  1. base = Select(columns=(
  2. Value(1).alias('n'),
  3. Value(0).alias('fib_n'),
  4. Value(1).alias('next_fib_n'))).cte('fibonacci', recursive=True)
  5. n = (base.c.n + 1).alias('n')
  6. recursive_term = Select(columns=(
  7. n,
  8. base.c.next_fib_n,
  9. base.c.fib_n + base.c.next_fib_n)).from_(base).where(n < 10)
  10. fibonacci = base.union_all(recursive_term)
  11. query = fibonacci.select_from(fibonacci.c.n, fibonacci.c.fib_n)
  12. results = list(query.execute(db))
  13. # Generates the following result list:
  14. [{'fib_n': 0, 'n': 1},
  15. {'fib_n': 1, 'n': 2},
  16. {'fib_n': 1, 'n': 3},
  17. {'fib_n': 2, 'n': 4},
  18. {'fib_n': 3, 'n': 5},
  19. {'fib_n': 5, 'n': 6},
  20. {'fib_n': 8, 'n': 7},
  21. {'fib_n': 13, 'n': 8},
  22. {'fib_n': 21, 'n': 9},
  23. {'fib_n': 34, 'n': 10}]

More

For a description of the various classes used to describe a SQL AST, see the query builder API documentation.

If you’re interested in learning more, you can also check out the project source code.