pythonponyorm

Maintaining foreign key relations when casting to dict


Say I have the following db classes:

class Person(DB.Entity):
  id = PrimaryKey(int, auto=True)
  name = Required(str, 100)
  cars = Set('Car')
class Car(DB.Entity):
  id = PrimaryKey(int, auto=True)
  owner = Required(Person, cascade_delete=False)

When I perform a select on Person, I get the associated cars:

people = Person.select(lambda p: p.name == 'Jaewon')

However, I would like to return people as a Dict instead of a Pony object, so it can be used in the calling methods. If I do the following, I get people as a dictionary, but lose the car key:

return people[:]

What is the proper way to pull values from the database and return them as dict without dropping their associated values?


Solution

  • The Entity.to_dict function has a related_objects keyword argument.

    You can use it to include the objects in the dicts.

    If you want the to-many relationships too, you also need the with_collections argument.

    people = Person.select(lambda p: p.name == 'Jaewon')
    
    people = [
      person.to_dict(
        related_objects=True,
        with_collections=True
      )
      for person in people
    ]
    

    This doesn't automatically recurse, and you will have to walk the tree yourself to create the full dict.

    for person in people:
      person['cars'] = [car.to_dict(**kwargs) for car in person['cars']]