Pony ORM

0.7.19 · active · verified Thu Apr 16

Pony ORM is a Python Object-Relational Mapper that allows developers to work with databases using Python objects and queries written in plain Python. It translates Python queries into optimized SQL, supporting SQLite, PostgreSQL, MySQL, and Oracle. The current version is 0.7.19. Releases occur periodically, often driven by new Python version support or significant bugfixes, indicating an active but not rapid development cadence with several months to a year between minor releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a database connection, creating entity models, generating the database schema, and performing basic CRUD operations within a `db_session` context. It uses an in-memory SQLite database for simplicity.

from pony.orm import *

db = Database()

class Person(db.Entity):
    id = PrimaryKey(int, auto=True)
    name = Required(str)
    age = Optional(int)
    cars = Set('Car')

class Car(db.Entity):
    make = Required(str)
    model = Required(str)
    owner = Required(Person)

db.bind(provider='sqlite', filename=':memory:', create_db=True)
db.generate_mapping(create_tables=True)

@db_session
def create_data():
    p1 = Person(name='John Doe', age=30)
    c1 = Car(make='Toyota', model='Camry', owner=p1)
    p2 = Person(name='Jane Smith', age=25)
    print("Data created.")

@db_session
def query_data():
    for p in select(p for p in Person if p.age < 35):
        print(f"Name: {p.name}, Age: {p.age}")
        for car in p.cars:
            print(f"  Car: {car.make} {car.model}")

create_data()
query_data()

view raw JSON →