Lesson

Pony ORM Relations: A Table That Points to Another Table

Connect two tables that point to each other as Python classes with Pony ORM, follow the relation in both directions, read the SQL that runs, and load related rows from a CSV file, with real World Bank data.

Last updated:


Where did life expectancy rise the most?

To answer, keep a table with the life expectancy of several countries in two years, and the income level of the country next to each measurement.
Then the name of a country and its income level are written again on every row of that country, and this causes two problems.
The first: when the classification of a country changes, it must be corrected on every row, and one row that is forgotten puts the same country on two income levels.
The second: a typo in a name, such as 'Isreal', splits one country into two.
The remedy is to keep each country once, and give each measurement a pointer to its country:
two tables that point to each other.

This lesson builds on Tables as Python Objects: A First Look at Pony ORM, which taught entities, with db_session:, select, get, the summary functions and first().

The examples run in your browser: select Run from top to bottom, because the boxes of this page share their variables with each other, and not with the boxes of Tables as Python Objects.
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 of both lessons are one set: a heading in each notebook marks where this lesson starts, and its tasks are numbered 9 to 13, after tasks 1 to 8 of Tables as Python Objects.

In the SQL guide, the department column of a table of employees holds the primary key of a row in another table, the departments.
A column like that is a foreign key, and a JOIN follows it to put each row next to the row it points to.
When one row of the first table is pointed to by many rows of the second, as one country is pointed to by its yearly measurements, this is a one-to-many relation.
An ORM writes the same link as attributes: an observation object holds its country object, and a country object holds all of its observation objects.

The data are real and come from the World Bank’s World Development Indicators (license CC BY 4.0), retrieved through the World Bank API:
the first two indicators on 30 October 2026 and the third on 8 November 2026.
Three indicators are used. SP.DYN.LE00.IN is the life expectancy at birth:
the number of years a newborn would live if the death rates of that year stayed the same for life.
NY.GDP.PCAP.PP.CD is the GDP per capita, PPP: the value of what a country produces in a year per person, in current international dollars, a unit that corrects for differences in prices between countries.
SP.POP.TOTL is the total population: the number of residents of a country, as the World Bank estimates it for the middle of the year.
The extract has 10 countries chosen to span regions and income levels, for the years 2000 and 2020.
The income level of each country is the World Bank’s own classification, as published at retrieval.

Three cautions come with the data. A few countries are not the world, so the extract can show a pattern but not measure it.
Two measurements that move together are an association and not a proof that one causes the other.
Also, a value that the source does not have stays missing: it is not zero.
The GDP of Syria in 2000 is missing in the source.

Your turn: one country has many measurements, and each measurement has one country.
How do you describe this in two classes, and in which of them is the pointer stored?

Show a solution

The class of the measurements, Observation, has an attribute country that points to one country.
The class of the countries, Country, has an attribute observations that holds all the measurements that point to the country, and it is not a column of the table.

The first line of the next box brings in the names of Pony, and geo is the database object of this lesson.
A few names describe the relation and the new kinds of columns:

  • Set('Observation') is the attribute observations of a country. It holds the set of all the observations that point to that country, and it is not a column of the table: Pony reads it from the column on the other side. The class name is in quotes because Observation is defined below it.
  • Required(Country) is the attribute country of an observation. Its value must be one Country object, so every observation belongs to a country. Optional(Country) would allow an observation with no country.
  • Optional(float) is a number with a decimal point that may be missing, and Optional(int) is a whole number that may be missing; a missing value is None.

The function show(Observation) prints the description of an entity as Pony understood it:
its attributes and their kinds, including the id that Pony added.
The id is a primary key that Pony chooses when we do not. We can choose our own:
with code = PrimaryKey(str) the code of a country is its primary key, Pony adds no id, and a country is found by Country['ISR'].
This lesson keeps the id.

from pony.orm import *

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

class Country(geo.Entity):
    code = Required(str)
    name = Required(str)
    income_level = Required(str)
    observations = Set('Observation')

class Observation(geo.Entity):
    year = Required(int)
    life_expectancy = Optional(float)
    gdp_per_capita = Optional(float)
    population = Optional(int)
    country = Required(Country)

geo.generate_mapping(create_tables=True)
show(Observation)
class Observation(Entity):
    id = PrimaryKey(int, auto=True)
    year = Required(int)
    life_expectancy = Optional(float)
    gdp_per_capita = Optional(float)
    population = Optional(int)
    country = Required(Country)

Create the objects and connect them

The extract is two lists of tuples: the countries, and the observations, each with the code of its country, the year, the life expectancy, the GDP per capita and the population.
The values are rounded, and the rounding changes no result in the lesson.
In practice such rows usually come from a file, and the section Rows from a file shows how to load them from one.
Here we write them in the code so that we can concentrate on creating the objects and connecting them.

country_rows = [
    ('ISR', 'Israel', 'High income'),
    ('JPN', 'Japan', 'High income'),
    ('USA', 'United States', 'High income'),
    ('NOR', 'Norway', 'High income'),
    ('BRA', 'Brazil', 'Upper middle income'),
    ('CHN', 'China', 'Upper middle income'),
    ('EGY', 'Egypt, Arab Rep.', 'Lower middle income'),
    ('IND', 'India', 'Lower middle income'),
    ('ETH', 'Ethiopia', 'Low income'),
    ('SYR', 'Syrian Arab Republic', 'Low income'),
]
print(len(country_rows))
10
observation_rows = [
    ('ISR', 2000, 78.954, 25746.83, 6289000),
    ('ISR', 2020, 82.649, 40969.3, 9215100),
    ('JPN', 2000, 81.076, 27694.54, 126843000),
    ('JPN', 2020, 84.56, 43560.02, 126261000),
    ('USA', 2000, 76.637, 36329.97, 282162411),
    ('USA', 2020, 76.98, 64465.3, 331578104),
    ('NOR', 2000, 78.634, 36813.84, 4490967),
    ('NOR', 2020, 83.21, 69779.29, 5379475),
    ('BRA', 2000, 69.584, 9091.77, 174018282),
    ('BRA', 2020, 74.506, 16101.62, 208660842),
    ('CHN', 2000, 72.288, 2963.43, 1262645000),
    ('CHN', 2020, 78.019, 18267.48, 1411100000),
    ('EGY', 2000, 67.332, 5451.52, 73083284),
    ('EGY', 2020, 69.79, 15231.87, 109315124),
    ('IND', 2000, 62.749, 2030.77, 1057922733),
    ('IND', 2020, 70.156, 6766.06, 1402617695),
    ('ETH', 2000, 50.88, 473.9, 67411494),
    ('ETH', 2020, 65.969, 2406.79, 118917671),
    ('SYR', 2000, 70.856, None, 16637888),
    ('SYR', 2020, 71.944, 3878.43, 21049429),
]
print(len(observation_rows))
20

The values of a dictionary can be any objects, not only numbers and text:
here the keys are the country codes and the values are the Country objects.
To create an observation of a country, we look the country object up by its code and pass it as country=....
That connects the two rows: Pony stores the key of the country in the column country of the observation.
The value None in a row goes into an Optional column as a missing value.

with db_session:
    countries = {}
    for code, name, income in country_rows:
        countries[code] = Country(
            code=code, name=name, income_level=income
        )
    for code, year, life, gdp, people in observation_rows:
        Observation(
            year=year, life_expectancy=life,
            gdp_per_capita=gdp, population=people,
            country=countries[code]
        )
    print(
        Country.select().count(),
        Observation.select().count()
    )
10 20

Follow the relation in both directions

Inside a db_session, a dot follows the relation. For an observation obs, obs.country is its Country object, and obs.country.name is the name of that country.
In the other direction, country.observations is the set of the observations of a country.
A set can be looped over like a list, and it has three methods:
count() returns the number of objects in it, order_by(...) sorts it as for a query, and select(...) keeps the objects for which the function you give is true.
To take one object by its place, as from a list, first turn the result of order_by or select into a list with list(...).
The function round(x, 1) rounds x to one digit after the decimal point.

with db_session:
    israel = Country.get(code='ISR')
    print(israel.name, israel.income_level)
    print(israel.observations.count())
    in_2020 = list(
        israel.observations.select(lambda o: o.year == 2020)
    )
    obs = in_2020[0]
    print(
        obs.country.name, obs.year,
        round(obs.life_expectancy, 1)
    )
Israel High income
2
Israel 2020 82.6

The method first() works on a set of related objects as well:
the box takes the latest observation of Israel, then looks for a year with no observation:

with db_session:
    israel = Country.get(code='ISR')
    latest = israel.observations.order_by(
        lambda o: desc(o.year)
    ).first()
    print(latest.year, round(latest.life_expectancy, 1))
    missing = israel.observations.select(
        lambda o: o.year == 1990
    ).first()
    print(missing)
2020 82.6
None

For each country, list(country.observations.order_by(lambda o: o.year)) holds its two observations, the earlier year first:
the index [0] is 2000 and [1] is 2020. The change in life expectancy is the value of 2020 minus the value of 2000.
We collect each change with the name of its country in a list of tuples, and sorted(..., reverse=True) puts the largest change first:

with db_session:
    gains = []
    for country in Country.select():
        years = list(
            country.observations.order_by(lambda o: o.year)
        )
        early = years[0].life_expectancy
        late = years[1].life_expectancy
        gains.append((round(late - early, 1), country.name))
    ranked = sorted(gains, reverse=True)
    print(ranked[:3])
    print(ranked[-1])
[(15.1, 'Ethiopia'), (7.4, 'India'), (5.7, 'China')]
(0.3, 'United States')

Life expectancy rose in every country, most in Ethiopia, which started lowest.
The extract does not say why: the smallest change, 0.3 years in the United States, can come from the long trend, from the pandemic of 2020, or from both, and two points cannot separate them.

Self-study, importance 4 This part is for self-study: it is not taught in the lecture, and you read it on your own. The second question of this section: the GDP per capita and a missing value. It helps with: a missing value in a calculation over related objects.

For the GDP per capita, a value can be missing, and then there is nothing to divide.
The loop keeps the countries without a value apart (x is None is true when x is missing), and for the others it computes how many times the GDP grew, the value of 2020 divided by the value of 2000:

with db_session:
    multiples = []
    missing = []
    for country in Country.select():
        years = list(
            country.observations.order_by(lambda o: o.year)
        )
        early = years[0].gdp_per_capita
        late = years[1].gdp_per_capita
        if early is None or late is None:
            missing.append(country.name)
        else:
            multiples.append(
                (round(late / early, 1), country.name)
            )
    print(sorted(multiples, reverse=True)[:3])
    print('missing:', missing)
[(6.2, 'China'), (5.1, 'Ethiopia'), (3.3, 'India')]
missing: ['Syrian Arab Republic']

Self-study, importance 2 This part is for self-study: it is not taught in the lecture, and you read it on your own. Conditions and sums that cross the relation, and task 9. It helps with: a condition that follows a relation, and a sum over the related objects of each object.

A condition across the relation

Inside a query, a dot can follow the relation as well: o.country.income_level is the income level of the country of the observation o.
Such a query needs both tables, and Pony writes the join that the SQL guide wrote by hand.
We group the observations of 2020 by income level and average the two indicators; avg skips the missing values:

with db_session:
    by_level = select(
        (
            o.country.income_level,
            avg(o.life_expectancy),
            avg(o.gdp_per_capita)
        )
        for o in Observation if o.year == 2020
    )
    print(by_level.get_sql())
    by_gdp = sorted(by_level, key=lambda row: row[2])
    for level, life, gdp in by_gdp:
        print(level, round(life, 1), round(gdp))
SELECT "country"."income_level", AVG("o"."life_expectancy"), AVG("o"."gdp_per_capita")
FROM "Observation" "o", "Country" "country"
WHERE "o"."year" = 2020
  AND "o"."country" = "country"."id"
GROUP BY "country"."income_level"
Low income 69.0 3143
Lower middle income 70.0 10999
Upper middle income 76.3 17185
High income 81.8 54693

The WHERE has the condition on the year and the line that connects the foreign key "o"."country" to the primary key "country"."id", as ON does in a JOIN.
On income level: higher income levels go with a longer life expectancy here, an association between averages of two to four countries.

A sum over countries of the same level

A population is counted in people, so it can be added: sum adds the number of residents of the measurements of the countries of one income level.
GDP per capita is a ratio, GDP divided by population, so adding it across countries is not the GDP per capita of all of them.

Your turn. Inside a with db_session: block, print for each income level how many people lived in 2020 in the countries of that level in the extract, in millions rounded to a whole number:
one line for each level, with the income level, a space and the number, from the level with the most residents to the level with the fewest.

# your code here
Show a hint

Return a pair, o.country.income_level and the sum(...) of the population, over the observations of 2020, as in the grouping above.
Sort the pairs with sorted(..., key=lambda row: row[1], reverse=True), and divide by 1000000 before rounding.

Show a solution
with db_session:
    totals = select(
        (o.country.income_level, sum(o.population))
        for o in Observation if o.year == 2020
    )
    for level, people in sorted(
        totals, key=lambda row: row[1], reverse=True
    ):
        print(level, round(people / 1000000))
Upper middle income 1620
Lower middle income 1512
High income 472
Low income 140

Brazil and China together are about 1,620 million residents in 2020, and Egypt and India about 1,512 million.

GDP per capita is not added like this. On the low income level, Ethiopia has 2,407 dollars per person and 118,917,671 residents, and Syria has 3,878 dollars per person and 21,049,429 residents.
The GDP per capita of both together is the total GDP divided by the total population:
(2,407 times 118,917,671 plus 3,878 times 21,049,429) divided by 139,967,100, about 2,628 dollars, and not 3,143, the average of the two countries.

Show a common mistake and why it happens
with db_session:
    totals = select(
        (o.country.income_level, sum(o.population))
        for o in Observation
    )
    for level, people in sorted(
        totals, key=lambda row: row[1], reverse=True
    ):
        print(level, round(people / 1000000))

The condition if o.year == 2020 is missing, so sum adds the population of both years, 2000 and 2020, of each country.
The population of one year can be added across countries, but adding across years counts the same people twice.

Show a common mistake and why it happens
with db_session:
    totals = select(
        (o.country.income_level, sum(o.gdp_per_capita))
        for o in Observation if o.year == 2020
    )
    for level, total in sorted(
        totals, key=lambda row: row[1], reverse=True
    ):
        print(level, round(total / 1000000))

Here sum adds the GDP per capita of the countries, and not the number of residents.
GDP per capita is a ratio, so its sum is not a number of people and not the GDP per capita of the level.
To count people, add population.

Self-study, importance 3 This part is for self-study: it is not taught in the lecture, and you read it on your own. The SQL that Pony sends while a relation is followed, and a sum over the collection of one country. It helps with: the SQL that Pony sends, and a sum over the related objects of one object.

A sum over the collection of one country

The set country.observations of one country can be added up too, with Python’s own sum:
sum(o.population for o in collection) adds o.population of every object of the collection.
Here we go over the set itself and keep the observations of Israel in 2020:

with db_session:
    israel = Country.get(code='ISR')
    print(sum(
        o.population for o in israel.observations
        if o.year == 2020 and o.population is not None
    ))
9215100

A country has one observation for each year, so the collection has one object and the sum has one term:
the box shows the form, not a larger total. The trap: the box goes over the set itself, so Python adds the values one by one and cannot add None to a number:
it stops with a TypeError, the error for a value of the wrong kind.
The sum of a query made with select(...) is different: it becomes SQL, and the database skips a missing value.
The column population is Optional(int), so if o.population is not None keeps only objects with a value.

The SQL that actually runs

The function set_sql_debug(True) is wider than get_sql, which shows one query:
until set_sql_debug(False), Pony prints every SQL command as it sends it to the database, with a few lines about the connection.
Here it shows what following a relation costs:

with db_session:
    set_sql_debug(True)
    norway = Country.get(code='NOR')
    print(norway.observations.count())
    set_sql_debug(False)
GET CONNECTION FROM THE LOCAL POOL
SWITCH TO AUTOCOMMIT MODE
SELECT "id", "code", "name", "income_level"
FROM "Country"
WHERE "code" = ?
LIMIT 2
['NOR']

SELECT COUNT(*)
FROM "Observation"
WHERE "country" = ?
[4]

2

A database that already exists

A database file that exists already, made by another program, is connected with its file name:
geo.bind(provider='sqlite', filename='wdi_extract.db'). Without the argument create_db=True, Pony does not create the file, so a wrong file name is an error and not a new empty database.
The call generate_mapping() without create_tables=True creates nothing:
it checks that the tables of the file exist with the names and columns that the classes describe, and it stops with an error if they do not match.

The block below is shown and not run, because it needs the file.
We made the file wdi_extract.db in advance, from the classes of this section with create_db=True:

geo = Database()
geo.bind(provider='sqlite', filename='wdi_extract.db')

# the classes Country and Observation, exactly as in the first box

geo.generate_mapping()

with db_session:
    israel = Country.get(code='ISR')
    print(israel.name, israel.observations.count())
Israel 2

Self-study, importance 1 This part is for self-study: it is not taught in the lecture, and you read it on your own. Loading rows from a CSV file, the practice tasks and the summary of the lesson. It helps with: creating many objects from the rows of a file.

Rows from a file

A table often arrives as a CSV file, with the names of the columns on the first line.
The file world-bank-more-countries.csv has the same three indicators, with full values and no rounding, for four more countries, for the years 2000 and 2020, with one line for each country and year.
The source and the license are those of the extract above; the first two indicators in the file were retrieved on 5 November 2026 and the population on 8 November 2026.
The GDP per capita of Eritrea for 2020 is missing in the source, so that field in the file is empty.

Python reads such a file with the module csv. The function open(name, newline='', encoding='utf-8') opens a file, and a with block closes it when the block ends; the option newline='' is what the module csv asks for.
The function csv.DictReader(file) goes over the lines after the first one, and gives each line as a dictionary whose keys are the names of the columns.
Every value that comes from a file is text, even a number, and an empty field is the empty text ''.
The function int(text) makes a whole number from text, and float(text) makes a number with a decimal point.

import csv

with open(
    'world-bank-more-countries.csv', newline='', encoding='utf-8'
) as file:
    rows = list(csv.DictReader(file))

print(len(rows))
print(rows[0]['name'], rows[0]['year'] * 2)
print(rows[0]['name'], int(rows[0]['year']) + 1)
print(rows[7]['gdp_per_capita'] == '')
8
Chile 20002000
Chile 2001
True

The year is text, so repeating it twice joins two copies of the text, and only int(...) makes it a number that can be added to.
A missing value must not become a number: an empty field becomes None with a conditional expression, float(text) if text != '' else None.

Loading the lines into entities is the loop of Create the objects and connect them, with row['code'] in place of the unpacked code.
A Country is created only the first time that its code appears:
the test code not in countries is true when the dictionary has no key code yet.
The method get takes several conditions at once: Observation.get(year=2020, country=some_country) returns the one observation that matches all of them.

Practice

Your turn. Create a database object wb_db in memory, as in this section.
Then write two entities, in this order. Economy has the attributes code and name, each a text that must have a value, and readings, a set of Reading objects.
Reading has indicator (a text that must have a value), year (a whole number that must have a value), value (a number with a decimal point that may be missing) and economy (an Economy object that must have a value).
Then create the tables with generate_mapping and call show(Reading).

# your code here
Show a hint

Each class is written with (wb_db.Entity) after its name. Reading is named inside Set(...) in quotes, because it is defined below Economy.

Show a solution
wb_db = Database()
wb_db.bind(provider='sqlite', filename=':memory:')

class Economy(wb_db.Entity):
    code = Required(str)
    name = Required(str)
    readings = Set('Reading')

class Reading(wb_db.Entity):
    indicator = Required(str)
    year = Required(int)
    value = Optional(float)
    economy = Required(Economy)

wb_db.generate_mapping(create_tables=True)
show(Reading)
class Reading(Entity):
    id = PrimaryKey(int, auto=True)
    indicator = Required(str)
    year = Required(int)
    value = Optional(float)
    economy = Required(Economy)

The attribute value is Optional(float), because a source can lack a value, and economy is Required(Economy), so every reading points to an economy.

Show a common mistake and why it happens
wb_db = Database()
wb_db.bind(provider='sqlite', filename=':memory:')

class Economy(wb_db.Entity):
    code = Required(str)
    name = Required(str)
    readings = Set('Reading')

class Reading(wb_db.Entity):
    indicator = Required(str)
    year = Required(int)
    value = Required(float)
    economy = Required(Economy)

wb_db.generate_mapping(create_tables=True)
show(Reading)

The attribute value is Required(float), so a reading with a missing value could not be stored.
The task asks for Optional.

Your turn. The classes Economy and Reading below are ready, names holds the name of each code, and rows holds real readings of two economies:
South Africa (ZAF) and Syria (SYR), whose GDP for 2000 is missing in the source.
In a with db_session: block, create a dictionary economies whose keys are the codes and whose values are Economy objects, then create a Reading for each row, connected to its economy through the dictionary.
Then print, for each code in the dictionary, the code and the number of its readings, with count().

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

class Economy(wb_db.Entity):
    code = Required(str)
    name = Required(str)
    readings = Set('Reading')

class Reading(wb_db.Entity):
    indicator = Required(str)
    year = Required(int)
    value = Optional(float)
    economy = Required(Economy)

wb_db.generate_mapping(create_tables=True)
names = {'ZAF': 'South Africa', 'SYR': 'Syrian Arab Republic'}
rows = [
    ('ZAF', 'life', 2000, 58.368),
    ('ZAF', 'life', 2020, 65.15),
    ('ZAF', 'gdp', 2020, 12671.0862436851),
    ('SYR', 'life', 2000, 70.856),
    ('SYR', 'life', 2020, 71.944),
    ('SYR', 'gdp', 2000, None),
    ('SYR', 'gdp', 2020, 3878.42802993832),
]

# your code here
Show a hint

In a with db_session: block, first loop over names and put Economy(code=..., name=...) in the dictionary under each code.
Then loop over rows, and pass economy=economies[code] to Reading.
A last loop over economies prints the code and economies[code].readings.count().

Show a solution
wb_db = Database()
wb_db.bind(provider='sqlite', filename=':memory:')

class Economy(wb_db.Entity):
    code = Required(str)
    name = Required(str)
    readings = Set('Reading')

class Reading(wb_db.Entity):
    indicator = Required(str)
    year = Required(int)
    value = Optional(float)
    economy = Required(Economy)

wb_db.generate_mapping(create_tables=True)
names = {'ZAF': 'South Africa', 'SYR': 'Syrian Arab Republic'}
rows = [
    ('ZAF', 'life', 2000, 58.368),
    ('ZAF', 'life', 2020, 65.15),
    ('ZAF', 'gdp', 2020, 12671.0862436851),
    ('SYR', 'life', 2000, 70.856),
    ('SYR', 'life', 2020, 71.944),
    ('SYR', 'gdp', 2000, None),
    ('SYR', 'gdp', 2020, 3878.42802993832),
]

with db_session:
    economies = {}
    for code in names:
        economies[code] = Economy(code=code, name=names[code])
    for code, indicator, year, value in rows:
        Reading(
            indicator=indicator, year=year, value=value,
            economy=economies[code]
        )
    for code in economies:
        print(code, economies[code].readings.count())
ZAF 3
SYR 4

South Africa has three readings and Syria has four, one of them with a missing value, which is stored as a row and not skipped.

Show a common mistake and why it happens
with db_session:
    economies = {}
    for code in names:
        economies[code] = Economy(code=code, name=names[code])
    for code, indicator, year, value in rows:
        Reading(
            indicator=indicator, year=year, value=value,
            economy=economies['ZAF']
        )
    for code in economies:
        print(code, economies[code].readings.count())

The dictionary is always asked for 'ZAF', so every reading is connected to South Africa, and Syria has none.
The key must come from the row: economies[code].

Your turn. The box below stores the economy with the code 'ZAF' and three of its readings.
In a new with db_session: block, get that economy with Economy.get(code='ZAF') and print the change in its life expectancy between 2000 and 2020, rounded to one digit after the decimal point:
the value of 2020 minus the value of 2000, using the readings with the indicator 'life'.

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

class Economy(wb_db.Entity):
    code = Required(str)
    name = Required(str)
    readings = Set('Reading')

class Reading(wb_db.Entity):
    indicator = Required(str)
    year = Required(int)
    value = Optional(float)
    economy = Required(Economy)

wb_db.generate_mapping(create_tables=True)

rows = [
    ('life', 2020, 65.15),
    ('life', 2000, 58.368),
    ('gdp', 2020, 12671.0862436851),
]

with db_session:
    zaf = Economy(code='ZAF', name='South Africa')
    for indicator, year, value in rows:
        Reading(
            indicator=indicator, year=year,
            value=value, economy=zaf
        )

# your code here
Show a hint

The set readings of the economy has the methods select and order_by.
Keep the readings whose indicator is 'life', sort them by year, and subtract the value at index [0] from the value at index [1].

Show a solution
wb_db = Database()
wb_db.bind(provider='sqlite', filename=':memory:')

class Economy(wb_db.Entity):
    code = Required(str)
    name = Required(str)
    readings = Set('Reading')

class Reading(wb_db.Entity):
    indicator = Required(str)
    year = Required(int)
    value = Optional(float)
    economy = Required(Economy)

wb_db.generate_mapping(create_tables=True)

rows = [
    ('life', 2020, 65.15),
    ('life', 2000, 58.368),
    ('gdp', 2020, 12671.0862436851),
]

with db_session:
    zaf = Economy(code='ZAF', name='South Africa')
    for indicator, year, value in rows:
        Reading(
            indicator=indicator, year=year,
            value=value, economy=zaf
        )

with db_session:
    zaf = Economy.get(code='ZAF')
    life = zaf.readings.select(
        lambda r: r.indicator == 'life'
    )
    years = list(life.order_by(lambda r: r.year))
    print(round(years[1].value - years[0].value, 1))
6.8

The two readings were created with the later year first, so the sort by year is what puts 2000 at index [0].

Show a common mistake and why it happens
with db_session:
    zaf = Economy.get(code='ZAF')
    life = list(
        zaf.readings.select(lambda r: r.indicator == 'life')
    )
    print(round(life[1].value - life[0].value, 1))

Without order_by, the readings come in the order in which they were created, and here the later year was created first, so the subtraction runs the wrong way and the sign changes.

Your turn. The classes FileCountry and FileObservation on the database file_db below are ready, and the file world-bank-more-countries.csv is in the working folder.
Read the file with csv.DictReader. In a with db_session: block, create a dictionary countries from each code to its FileCountry object, creating each country once, and create an FileObservation for each line, with the year and the population as whole numbers, and the life expectancy and the GDP per capita as numbers with a decimal point, or None when the field is empty.
Print the number of countries and the number of observations on one line, separated by a space, and on the next line the GDP per capita of Eritrea (ERI) in 2020.

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

class FileCountry(file_db.Entity):
    code = Required(str)
    name = Required(str)
    income_level = Required(str)
    observations = Set('FileObservation')

class FileObservation(file_db.Entity):
    year = Required(int)
    life_expectancy = Optional(float)
    gdp_per_capita = Optional(float)
    population = Optional(int)
    country = Required(FileCountry)

file_db.generate_mapping(create_tables=True)

# your code here
Show a hint

Import csv, open the file as in the box above, and make a list of the lines with list(csv.DictReader(file)).
In the block, loop over the lines: create the FileCountry only when its code is not yet a key of countries, and always create the FileObservation, with country=countries[code].
The last line is FileObservation.get(...) with the country and the year, and then the attribute gdp_per_capita.

Show a solution
import csv

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

class FileCountry(file_db.Entity):
    code = Required(str)
    name = Required(str)
    income_level = Required(str)
    observations = Set('FileObservation')

class FileObservation(file_db.Entity):
    year = Required(int)
    life_expectancy = Optional(float)
    gdp_per_capita = Optional(float)
    population = Optional(int)
    country = Required(FileCountry)

file_db.generate_mapping(create_tables=True)

with open(
    'world-bank-more-countries.csv', newline='', encoding='utf-8'
) as file:
    rows = list(csv.DictReader(file))

with db_session:
    countries = {}
    for row in rows:
        code = row['code']
        if code not in countries:
            countries[code] = FileCountry(
                code=code, name=row['name'],
                income_level=row['income_level']
            )
        life = row['life_expectancy']
        gdp = row['gdp_per_capita']
        FileObservation(
            year=int(row['year']),
            life_expectancy=float(life) if life != '' else None,
            gdp_per_capita=float(gdp) if gdp != '' else None,
            population=int(row['population']),
            country=countries[code]
        )
    print(FileCountry.select().count(), FileObservation.select().count())
    eritrea = FileObservation.get(
        country=countries['ERI'], year=2020
    )
    print(eritrea.gdp_per_capita)
4 8
None

Four countries and eight observations are stored, and the empty field of Eritrea became None and not a number.

Show a common mistake and why it happens
import csv

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

class FileCountry(file_db.Entity):
    code = Required(str)
    name = Required(str)
    income_level = Required(str)
    observations = Set('FileObservation')

class FileObservation(file_db.Entity):
    year = Required(int)
    life_expectancy = Optional(float)
    gdp_per_capita = Optional(float)
    population = Optional(int)
    country = Required(FileCountry)

file_db.generate_mapping(create_tables=True)

with open(
    'world-bank-more-countries.csv', newline='', encoding='utf-8'
) as file:
    rows = list(csv.DictReader(file))

with db_session:
    countries = {}
    for row in rows:
        code = row['code']
        countries[code] = FileCountry(
            code=code, name=row['name'],
            income_level=row['income_level']
        )
        life = row['life_expectancy']
        gdp = row['gdp_per_capita']
        FileObservation(
            year=int(row['year']),
            life_expectancy=float(life) if life != '' else None,
            gdp_per_capita=float(gdp) if gdp != '' else None,
            population=int(row['population']),
            country=countries[code]
        )
    print(FileCountry.select().count(), FileObservation.select().count())
    eritrea = FileObservation.get(
        country=countries['ERI'], year=2020
    )
    print(eritrea.gdp_per_capita)

A FileCountry is created for every line, without the test code not in countries, so there are eight countries and not four, two for each code.
The dictionary keeps only the last one of each code, which is why the second line still looks right.

Keep in mind

  • A one-to-many relation is a foreign key seen from both sides: Required(Country) or Optional(Country) on the many side, Set('Observation') on the one side. A dot follows it in both directions, and inside a query a dot such as o.country.income_level makes Pony write the join.
  • Optional(float) allows a missing value, which is None; test it with is None before calculating. A missing value is not zero.
  • A dictionary from a code to an object (countries[code]) connects new objects to the right related object.
  • csv.DictReader reads a CSV file: every value is text, so convert it with int(...) or float(...), and turn an empty field into None.
  • show(Entity) prints how Pony understood an entity, and set_sql_debug(True) prints every SQL command that runs. To use a database file that exists, bind it without create_db=True and call generate_mapping() without create_tables=True.