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:

  1. class Person(db.Entity):
  2. cars = Set('Car')
  3. class Car(db.Entity):
  4. 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:

  1. from pony.orm import *
  2. db = Database()
  3. class Person(db.Entity):
  4. name = Required(str)
  5. cars = Set('Car')
  6. class Car(db.Entity):
  7. make = Required(str)
  8. model = Required(str)
  9. owner = Optional(Person)
  10. db.bind('sqlite', ':memory:')
  11. db.generate_mapping(create_tables=True)

Now let’s create instances of Person and Car entities:

  1. >>> p1 = Person(name='John')
  2. >>> c1 = Car(make='Toyota', model='Camry')
  3. >>> 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.