Chapter 11.3.3. Joins

You can also use various forms of Join expression with the select() method of model classes. The following code gets the list of authors (people who have published a book):

authors = Person.select(join=INNERJOINOn(Person, Book, Person.q.id == Book.
q.author_id), distinct=True)
for a in authors:
    print a

Output:

<Person 1 firstName='Stephen' lastName='King'>
<Person 2 firstName='Donald' lastName='Knuth'>

Here is the generated SQL:

SELECT DISTINCT person.id, person.first_name, person.last_name FROM person INNER
JOIN book ON (person.id = book.author_id) WHERE 1 = 1

Let’s take it apart piece by piece. We pass two named arguments (join and distinct) to the Person.select() method. The join argument is an INNERJOINOn sqlbuilder ...

Get Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.