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?
The
Entity.to_dictfunction has arelated_objectskeyword 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_collectionsargument.This doesn't automatically recurse, and you will have to walk the tree yourself to create the full dict.