Using Python generator expressions

Pony allows to use generator expressions as a very natural way of writing database queries. Pony provides select() function which accepts Python generator, translates it to SQL and returns objects from the database. The process of the translation is described in this StackOverflow question.

Here is an example of a query:

  1. query = select(c for c in Customer
  2. if sum(o.total_price for o in c.orders) > 1000)

or, with attribute lifting:

  1. query = select(c for c in Customer
  2. if sum(c.orders.total_price) > 1000)

You can apply filter() function to query

  1. query2 = query.filter(lambda person: person.age > 18)

Also you can make new query based on another query:

  1. query3 = select(customer.name for customer in query2
  2. if customer.country == 'Canada')

select() function returns an instance of a Query class, and you can then call the Query object methods for getting the result, for example:

  1. customer_name = query3.first()

From query you can return entity, attribute or tuple of arbitrary expressions

  1. select((c, sum(c.orders.total_price))
  2. for c in Customer if sum(c.orders.total_price) > 1000)