Lesson

Tables as Python Objects: A First Look at Pony ORM

Describe a database table as a Python class, add, read, summarize, change and delete rows as objects, and let Pony ORM write the SQL from a generator expression.

Last updated:


Can a program use the rows of a table as ordinary objects?

The question is whether a row of a table can be kept in a variable, like any Python object, with its columns read by name, for example day.rentals, instead of reading a value from a tuple by its position.
To see why that matters, here are two problems of the way we have worked so far.

In SQL from Python, the program sent SQL as text and got tuples back.
Python does not check the text of a query, so a typo in a column name shows up only when the line runs, as the error no such column: total_ride:

c.execute("SELECT observation_date, total_ride FROM daily_ridership")

A second failure: a column of a tuple is read by its position, such as row[4], so when someone adds a column before total_rides, the same line of code will read another column, without reporting an error.
The people who rely on the numbers pay for it: the daily bike-share rentals report stops at night or shows another column.

An ORM (object-relational mapper) changes the division of work:
you describe a table as a Python class, each row becomes an object of that class, and the ORM writes the SQL for you.
This lesson uses Pony ORM, a Python library, and works on the bike-share days as before.

In Pony you write a query as a generator expression, as in the lesson on objects and generator expressions.
It is a Python expression that describes which items to take and under what condition, for example:

d for d in Day if d.season == 'Summer'

Pony does not run that expression as it stands; it reads its structure and translates it into SQL.
It is important to understand what each part of the expression says:
what comes before for is what to take, what comes after in is from where, and the condition after if is which items.
Each of them becomes a different part of the SQL query.

The examples run in your browser: select Run from top to bottom, because the boxes of the page share their variables.
If you press Stop or reload, run the page again from the top.
The first run of the page loads Pony, so it can take a moment.

The notebooks follow this page and Pony ORM relations cell by cell, with the same code and the same questions:
each notebook has a heading that marks where the second lesson starts.
The tasks of the notebooks are numbered from 1 to 13 without a break:
tasks 1 to 8 are the tasks of this page, and tasks 9 to 13 are those of the other lesson.
Their first cell installs Pony, and one more cell downloads a small CSV file from this site, so no key and no account setting is involved.

If the link does not open, open colab.research.google.com, choose File, then Upload notebook, and select the downloaded file.

Describe a table as a class

The object db represents the database that Pony works with. The first line of the next box, from pony.orm import *, brings in every name that Pony offers.
Database() creates db, and db.bind(...) connects it to SQLite; ':memory:' is again a temporary database in memory, as in SQL from Python.

from pony.orm import *

db = Database()
db.bind(provider='sqlite', filename=':memory:')

A class that stands for a table is called an entity. The class name is written with (db.Entity) after it, as in class Day(db.Entity):, and the brackets mark it as an entity of the database db:
Pony stores its objects as rows of a table named Day. Each column is a line that names the attribute and its kind:
Required(str) is a text that must have a value, and Required(int) is a whole number that must have a value.
After all the entities, db.generate_mapping(...) finishes the description of the tables; when create_tables=True the method also creates the table in the database, if the table does not exist yet.

class Day(db.Entity):
    date = Required(str)
    season = Required(str)
    working_day = Required(int)
    rentals = Required(int)

db.generate_mapping(create_tables=True)
print(list(db.entities))
['Day']

Pony also adds to the entity a column id that numbers the rows.
It is the primary key, so you did not need to write it.

Check yourself: how many columns does the created table Day have, and which of them did we not write?

Show the answer

Five: the four we wrote, and id. It is the primary key, a number that identifies each row, and Pony numbers it by itself, so a row that we add is written with the four columns of the entity only.
The four columns we wrote are Required, so every row must have a value for them.

Add rows as objects

In a program, Pony talks to the database only inside a with db_session: block (see db_session).
The block groups actions that must be saved together, like a bank transfer in which both the withdrawal from one account and the deposit into another must succeed.
When the block ends normally, Pony saves all the changes; if an error stops the block, Pony cancels all of them, and none of them is saved.
Creating a row is creating an object: call the class with the values of the columns.
After the loop, the box counts the rows of the table with Day.select().count() and fetches the object whose id is 1 with Day[1]; the text below the box explains both.

rows = [
    ('2011-01-01', 'Winter', 0, 985),
    ('2011-01-02', 'Winter', 0, 801),
    ('2011-01-03', 'Winter', 1, 1349),
    ('2011-07-04', 'Summer', 0, 6043),
    ('2011-07-05', 'Summer', 1, 4665),
    ('2011-07-06', 'Summer', 1, 4629),
]

with db_session:
    for date, season, working_day, rentals in rows:
        Day(
            date=date, season=season, working_day=working_day,
            rentals=rentals
        )
    print(Day.select().count())
    day = Day[1]
    print(day, day.date, day.rentals)
6
Day[1] 2011-01-01 985

The loop uses the unpacking from loops and functions, and the six rows are the real days from the SQL lessons.
Day[1] fetches the object whose primary key is 1. The values of its columns are called its attributes, and you read one by writing a dot after the object followed by the attribute name, as in day.date, exactly as in objects and generator expressions.
Printing the object shows the class name and the key. Use the objects inside the with db_session: block, where Pony is connected to the database.

Try it yourself. Inside a with db_session: block, print on one line the date, the season and the number of rentals of the day whose primary key is 4.

# your answer here
Show a hint

Fetch the object with Day[4], keep it in a variable, and read its attributes date, season and rentals with a dot.

Show a solution
with db_session:
    day = Day[4]
    print(day.date, day.season, day.rentals)
2011-07-04 Summer 6043

Day[4] fetches the day whose primary key is 4, and reading the three attributes with a dot prints the date, the season and the number of rentals.

Show a common mistake and why it happens
with db_session:
    day = Day[4]
    print(day)

Printing the object itself shows only the class name and the key, Day[4].
To see the values you read its attributes one by one, such as day.date.

What happens outside a db_session block

Every use of entities belongs inside with db_session:: creating an object, running a query and reading related objects.
Run the box below, which uses the definitions from the boxes above and runs a query without the block.
It stops with an error, as it does in a program that Python runs from a file.
Python shows the lines of the box that led to the error, and the last line says what is missing.

print(Day.select().count())
pony.orm.core.TransactionError: db_session is required when working with the database

The error is the point of the box, so it is not a mistake in the page.
Putting the line inside with db_session: fixes it, as in the boxes above.

Pony in a notebook (Jupyter or Colab)

When Pony is first imported, it checks what kind of environment it is running in, and decides from that how strictly to require the with db_session: block.
A program that Python runs from a file is not interactive, meaning nobody types a line and sees the result right away, so a query outside the block stops there with an error.
A notebook (Jupyter or Colab) is an interactive console: Pony notices that and lets a query run outside with db_session:.
The same line print(Day.select().count()) prints the number of rows there instead of stopping with an error.

Keep writing with db_session: in a notebook anyway. The code then works unchanged when it moves into a program, and the end of the block is where Pony saves the changes, or cancels them after an error.
In Colab, Pony is installed with pip install pony in a cell, because Colab does not include it.

Read rows: a query as a generator expression

select(...) takes a generator expression. The part before for says what to return, the part after in says which entity, and the condition after if filters the rows, just like SELECT, FROM and WHERE.
Looping over the result runs the query and gives one object for each row.
The method order_by sorts the rows of a result by the value of the small function you give it, and desc(...) makes the order from the largest down, like ORDER BY ... DESC.

with db_session:
    summer = select(d for d in Day if d.season == 'Summer')
    for d in summer.order_by(lambda d: desc(d.rentals)):
        print(d.date, d.rentals)
2011-07-04 6043
2011-07-05 4665
2011-07-06 4629

An entity column is read by its name, such as d.rentals, so the order of the columns does not matter, and a wrong name such as d.rentalz stops at the line of the query, with a message that names it.

To see the SQL that Pony wrote, the method get_sql of a query returns it as text:

with db_session:
    print(
        select(
            d for d in Day if d.season == 'Summer'
        ).get_sql()
    )
SELECT "d"."id", "d"."date", "d"."season", "d"."working_day", "d"."rentals"
FROM "Day" "d"
WHERE "d"."season" = 'Summer'

This is a query you could have typed in DB Browser. Pony also uses the parameters of SQL from Python:
a Python variable inside the expression is not pasted into the text, but sent as a value for a question mark.

with db_session:
    limit = 4600
    busy = select(d for d in Day if d.rentals > limit)
    print(busy.get_sql())
    print([d.date for d in busy])
SELECT "d"."id", "d"."date", "d"."season", "d"."working_day", "d"."rentals"
FROM "Day" "d"
WHERE "d"."rentals" > ?
['2011-07-04', '2011-07-05', '2011-07-06']

A slice takes the first rows only, as with a list: select(...)[:2] returns the first two objects.

When only one object is needed, the method first() is shorter than list(...)[0].
It returns the first object of a result, and None when the result is empty, where list(...)[0] stops with an error on an empty list.

first() differs from the slice [:1] as well: the slice returns a list that holds at most one object, and first() returns the object itself.
After order_by(...), the first object is the first in that order.
The box takes the day with the fewest rentals, and then asks for a day above 10000 rentals, which does not exist:

with db_session:
    quietest = select(d for d in Day).order_by(
        lambda d: d.rentals
    ).first()
    print(quietest.date, quietest.rentals)
    huge = select(d for d in Day if d.rentals > 10000).first()
    print(huge)
2011-01-02 801
None

The first call returns an object, whose attributes are read by writing a dot and then the attribute name, and the second finds no day and returns None, so check for None before reading an attribute of the result.

Practice

Your turn. Inside a with db_session: block, print the dates of the days of 'Winter', one on each line, from the earliest date to the latest.

# your code here
Show a hint

Keep the winter days with a condition after if, sort the result with order_by(lambda d: d.date), and loop over it to print one attribute on each line.

Show a solution
with db_session:
    winter = select(d for d in Day if d.season == 'Winter')
    for d in winter.order_by(lambda d: d.date):
        print(d.date)
2011-01-01
2011-01-02
2011-01-03

Winter has three days, so three dates are printed, in date order.

Show a common mistake and why it happens
with db_session:
    winter = select(d for d in Day if d.season == 'Winter')
    for d in winter.order_by(lambda d: d.rentals):
        print(d.date)

order_by sorts by the expression you give it. Here it sorts by the number of rentals, so the three dates are printed from the day with the fewest rentals to the day with the most, and not in date order.

Show a common mistake and why it happens
with db_session:
    winter = select(d for d in Day if d.season == 'Winter')
    print([d.date for d in winter.order_by(lambda d: d.date)])

The loop is missing. print is called once, with the whole list, so the dates appear on one line inside square brackets instead of one on each line.

Summaries and groups

The summary functions of SQL have names in Pony too: count, sum, avg, min and max.
Each takes a generator expression that gives the values to summarize; sum, min and max keep working on ordinary lists, as in values and collections.

with db_session:
    print(count(d for d in Day))
    print(avg(d.rentals for d in Day if d.season == 'Summer'))
    print(max(d.rentals for d in Day))
    print(sum(d.rentals for d in Day if d.working_day == 1))
6
5112.333333333333
6043
10643

When the expression returns a pair, such as the season and a summary, Pony groups by the part that is not summarized:

with db_session:
    by_season = select(
        (d.season, avg(d.rentals)) for d in Day
    )
    print(by_season.get_sql())
    print(list(by_season))
SELECT "d"."season", AVG("d"."rentals")
FROM "Day" "d"
GROUP BY "d"."season"
[('Summer', 5112.333333333333), ('Winter', 1045.0)]

The same shape counts the rows of each group: with count(d) in the pair, where d is the whole day, Pony counts the days of each season.
It counts each day once, by its primary key, which is why the SQL that it writes includes COUNT(DISTINCT ...).

with db_session:
    days_per_season = select(
        (d.season, count(d)) for d in Day
    )
    print(days_per_season.get_sql())
    print(list(days_per_season))
SELECT "d"."season", COUNT(DISTINCT "d"."id")
FROM "Day" "d"
GROUP BY "d"."season"
[('Summer', 3), ('Winter', 3)]

The SQL has a GROUP BY that you did not write: the SQL guide, Part 1 taught it, and here the ORM adds it from the shape of the expression.

The same total in two ways

A question about a total can be answered by a loop in Python or by a summary function, and both give the same number.
The method select() of an entity, with no arguments, returns all its objects.
The loop below takes every day from the database and adds the rentals of the summer days one by one, in Python.
The summary function asks the database for the total instead.

Predict: both ways print the same number. Which of them moves fewer rows from the database into Python, and why?

with db_session:
    total = 0
    for d in Day.select():
        if d.season == 'Summer':
            total = total + d.rentals
    print(total)
    print(sum(d.rentals for d in Day if d.season == 'Summer'))
15337
15337
Show the answer

The answer is sum(...). The loop brings all the days into Python, and sum(...) makes Pony send one SELECT SUM(...) and receive one number.
For a table of many thousands of rows, the loop would still move every row into Python, and sum(...) would still receive one number.

A summary that feeds a second query

A summary is an ordinary Python value, so it can be stored in a variable and used in the next query.
The first query below finds the largest rentals with max, and Day.get(rentals=top) then returns the day with that value.

The method get expects exactly one match: when two days share the value, Pony stops with an error, and select(...).first() is the way to take one of them.

The second query finds the average rentals of all days with avg, and a query keeps the days above it.
Pony sends the stored value as a parameter, as in the query with limit above.

with db_session:
    top = max(d.rentals for d in Day)
    busiest = Day.get(rentals=top)
    print(busiest.date, top)

    mean = avg(d.rentals for d in Day)
    above = select(d for d in Day if d.rentals > mean)
    print(round(mean), above.count())
2011-07-04 6043
3079 3

The average of the six days is about 3079, and three days have more rentals than that:
the three summer days.

Practice

Self-study, importance 2 This part is for self-study: it is not taught in the lecture, and you read it on your own. Practice that repeats the summary functions on the winter days. It helps with: summary functions (maximum, average) over a group of rows.

Your turn. Inside a with db_session: block, print the largest rentals among the winter days, using max, and on the next line the average rentals of the winter days, using avg.

# your code here
Show a hint

Each summary function takes a generator expression, and both lines need the same condition after if:
the season is 'Winter'.

Show a solution
with db_session:
    print(max(d.rentals for d in Day if d.season == 'Winter'))
    print(avg(d.rentals for d in Day if d.season == 'Winter'))
1349
1045.0

The largest winter day is 1349, and the average of 985, 801 and 1349 is 1045.0.

Show a common mistake and why it happens
with db_session:
    print(max(d.rentals for d in Day))
    print(avg(d.rentals for d in Day if d.season == 'Winter'))

The condition if d.season == 'Winter' is missing from the first line, so max looks at all six days and returns the summer maximum instead of the winter one.
A summary function only looks at the rows that the expression lets through.

Your turn. Inside a with db_session: block, store the average rentals of all the days in a variable.
Then print the dates of the days with fewer rentals than that average, one on each line, from the earliest date to the latest.

# your code here
Show a hint

Write the average in a variable inside the block, use that variable after if in a select(...), and sort the result with order_by(lambda d: d.date).

Show a solution
with db_session:
    mean = avg(d.rentals for d in Day)
    below = select(d for d in Day if d.rentals < mean)
    for d in below.order_by(lambda d: d.date):
        print(d.date)
2011-01-01
2011-01-02
2011-01-03

The average of all six days is about 3079, and the three winter days are below it.

Show a common mistake and why it happens
with db_session:
    mean = avg(d.rentals for d in Day if d.season == 'Winter')
    below = select(d for d in Day if d.rentals < mean)
    for d in below.order_by(lambda d: d.date):
        print(d.date)

The average is taken over the winter days only, about 1045, so only the day with 801 rentals is below it.
The question asks for the average of all the days.

Change and delete rows

To change a column, assign to the attribute of the object. To delete a row, call delete() on its object.
We first add a test day that is not real data, so that the real days stay as they are.
Day.get(...) returns the one object that matches, or None if there is none.
Predict: the second block sets rentals to 2, and the third is a new with db_session:.
What does the third print on its first line: 1, 2 or an error?

with db_session:
    Day(
        date='2099-01-01', season='Summer', working_day=1,
        rentals=1
    )

with db_session:
    test_day = Day.get(date='2099-01-01')
    test_day.rentals = 2
    print(test_day.rentals)

with db_session:
    print(Day.get(date='2099-01-01').rentals)
    Day.get(date='2099-01-01').delete()
    print(count(d for d in Day))
    print(Day.get(date='2099-01-01'))
2
2
6
None
Show the answer

The answer is 2. The third block is a new session with the database, and it sees the changed value:
the change was saved when the second block ended.

Compare this with SQL from Python, where you wrote UPDATE and DELETE as SQL text and decided when to call commit().
Here the end of the db_session block is the commit, and an error inside the block is the rollback.
The call commit() inside the block saves the changes made so far at once, and the block goes on.

Self-study, importance 1 This part is for self-study: it is not taught in the lecture, and you read it on your own. Cancelling a change on purpose, and practice on changing and deleting a test day. It helps with: changing and deleting rows, and cancelling a change inside a block.

You can also cancel on purpose: the call rollback() inside the block cancels every change made since the block began, as conn.rollback() does in the section on changing data and saving it, and the block then continues with the database as it was.

After a commit() inside the block, a later rollback() cancels only what came after the commit().
The box below adds a test day, saves it with commit(), adds a second test day and cancels it with rollback().
A new block then reads what the database holds, and deletes the first test day, so that the table has its six real days again:

with db_session:
    Day(
        date='2097-01-01', season='Summer', working_day=1,
        rentals=1
    )
    commit()
    Day(
        date='2097-01-02', season='Summer', working_day=1,
        rentals=2
    )
    rollback()

with db_session:
    print(Day.get(date='2097-01-01').rentals)
    print(Day.get(date='2097-01-02'))
    Day.get(date='2097-01-01').delete()
    print(count(d for d in Day))
1
None
6

The first test day was saved by commit(), so it is still there, and the second was cancelled before it was saved, so Day.get finds nothing and returns None.

Practice

Your turn. In one with db_session: block, create a test day with the date '2098-01-01', the season 'Winter', working_day 0 and rentals 10.
Change its rentals to 20 and print them. Then delete the day and print count(d for d in Day).

# your code here
Show a hint

Keep the object that Day(...) returns in a variable. Assign to its attribute rentals to change it, and call delete() on the object to remove the row.

Show a solution
with db_session:
    day = Day(
        date='2098-01-01', season='Winter', working_day=0,
        rentals=10
    )
    day.rentals = 20
    print(day.rentals)
    day.delete()
    print(count(d for d in Day))
20
6

After the day is deleted the table has its six original rows again.

Show a common mistake and why it happens
with db_session:
    day = Day(date='2098-01-01', season='Winter', working_day=0, rentals=10)
    day.rentals = 20
    print(day.rentals)
    print(count(d for d in Day))
    rollback()

The day was never deleted, so the count includes the extra row.
The rollback() at the end only cancels the test day, so that the other boxes of the page still see six days.

Show a common mistake and why it happens
with db_session:
    day = Day(date='2098-01-01', season='Winter', working_day=0, rentals=10)
    rentals = day.rentals
    rentals = 20
    print(day.rentals)
    day.delete()
    print(count(d for d in Day))

The line rentals = 20 changes a separate variable that holds a copy of the number, not the attribute of the object.
To change the column, assign to the attribute: day.rentals = 20.

Practice

Each question has its own code box: write your answer there and select Run.
Open a hint if you are stuck, and the solution only after you try.

Before the questions, notice what stays the same from the SQL lessons:
the tables, the keys and the thinking about which rows and which summary you need.
Only the way you write the request changes.

Question 1. Print the date and rentals of the working days (working_day is 1) with more than 4600 rentals, from the busiest day down.

# your answer here
Show a hint

Put both conditions after if, joined with and, and sort with the function:

order_by(lambda d: desc(d.rentals))

Loop over the result and print two attributes.

Show a solution
with db_session:
    days = select(
        d for d in Day
        if d.working_day == 1 and d.rentals > 4600
    )
    for d in days.order_by(lambda d: desc(d.rentals)):
        print(d.date, d.rentals)
2011-07-05 4665
2011-07-06 4629

These are the same two days as in SQL from Python, now with the filtering done in the database.

Show a common mistake and why it happens

Without desc(...), order_by sorts from the smallest value:

with db_session:
    days = select(d for d in Day if d.working_day == 1 and d.rentals > 4600)
    for d in days.order_by(lambda d: d.rentals):
        print(d.date, d.rentals)

Self-study, importance 3 This part is for self-study: it is not taught in the lecture, and you read it on your own. Questions 2 and 3, and the summary of the lesson. It helps with: grouping rows, and calculations inside a query.

Question 2. For each season, print how many days had more than 1000 rentals, one line for each season:
the season, a space, the number.

# your answer here
Show a hint

Return a pair, the season and count(d), and put the condition on d.rentals after if.

Show a solution
with db_session:
    for season, number in select(
        (d.season, count(d)) for d in Day if d.rentals > 1000
    ):
        print(season, number)
Summer 3
Winter 1

Only one winter day passes 1000 rentals, and all three summer days do.

Show a common mistake and why it happens

Without if d.rentals > 1000 the query counts all the days of each season:

with db_session:
    for season, number in select((d.season, count(d)) for d in Day):
        print(season, number)

Question 3. Add the real day '2011-07-07' (a summer working day with 4592 rentals), then print the average rentals of the summer days, rounded to a whole number.
Finish with rollback(), which cancels the new day, so that the other boxes of the page still see the same six days.

# your answer here
Show a hint

Create the object with Day(...) inside a db_session block, then call avg on a generator expression about the summer days.
Wrap it in round(...).

Show a solution
with db_session:
    Day(
        date='2011-07-07', season='Summer', working_day=1,
        rentals=4592
    )
    print(
        round(
            avg(
                d.rentals for d in Day if d.season == 'Summer'
            )
        )
    )
    rollback()
4982

Pony sends the new row to the database before it runs the query, so the average includes the day that was just added.
rollback() then cancels the new day.

Show a common mistake and why it happens
with db_session:
    print(
        round(
            avg(d.rentals for d in Day if d.season == 'Summer')
        )
    )
    Day(
        date='2011-07-07', season='Summer', working_day=1,
        rentals=4592
    )
    rollback()

The average is calculated before the new day is added, so it covers only the three summer days that were already there.
The day must be created first, and then the query sees it.

Keep in mind

  • An ORM maps a table to a class and a row to an object. Pony writes the SQL from a generator expression, so the form of the expression matters.
  • db.Entity classes describe tables, Required(...) describes a column, and db.generate_mapping(...) creates the tables.
  • Work with the database inside with db_session:: creating objects, running queries and reading related objects. A program that runs outside it stops with an error. The end of the block saves the changes, and an error inside cancels them.
  • select(...), count, avg, sum, min and max correspond to SELECT, COUNT, AVG, SUM, MIN and MAX; get_sql() shows the SQL that Pony wrote.
  • To change a column, assign to the attribute; to delete a row, call delete().
  • commit() inside the block saves the changes so far; a later rollback() cancels only what came after it.
  • A summary can be stored in a variable and used in a second query; get(...) returns the one object that matches and stops with an error when several do.
  • first() returns the first object of a query result, or None when it is empty.
  • A notebook lets a query run outside with db_session: and a program does not; keep the block in both.