Working with entity relationships
In Pony, an entity can relate to other entities through relationship attributes. Each relationship always has two ends, and is defined by two entity attributes:
class Person(db.Entity):
cars = Set('Car')
class Car(db.Entity):
owner = Optional(Person)
In the example above we’ve defined one-to-many relationship between the Person
and Car
entities using the Person.cars
and Car.owner
attributes.
Let’s add a couple more data attributes to our entities:
from pony.orm import *
db = Database()
class Person(db.Entity):
name = Required(str)
cars = Set('Car')
class Car(db.Entity):
make = Required(str)
model = Required(str)
owner = Optional(Person)
db.bind('sqlite', ':memory:')
db.generate_mapping(create_tables=True)
Now let’s create instances of Person
and Car
entities:
>>> p1 = Person(name='John')
>>> c1 = Car(make='Toyota', model='Camry')
>>> commit()
Normally, in your program, you don’t need to call the function commit()
manually, because it should be called automatically by the db_session()
. But when you work in the interactive mode, you never leave a db_session()
, that is why we need to commit manually if we want to store data in the database.