0

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?

1 Answer 1

1

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']]
2
  • This worked for the first level, thanks! Unfortunately, the cars object is still a list of Entities, and not a list of dicts. Do you know if there are any other options to convert to dict the whole way down, or should I just iterate over the values of person and cast them to dicts manually?
    – rgahan
    Oct 28, 2021 at 18:59
  • 1
    @rgahan You need to iterate over the objects and convert them to dicts all the way down. I've edited the answer to add the link for the documentation.
    – Ron
    Oct 28, 2021 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.