ponyorm

Accessing values from one-to-many relationship in PonyORM


For a database of games, where one game is called different names by different users, I have two tables, set up as one-to-many:

class Game(db.Entity):
    name = Set('Name')
    ...

class Name(db.Entity):
    game = Required(Game)
    name = Required(str)
    ...

How can I access the names for a specific game? They come back as "Multiset", which (I think) is a special Counter object, when I do this:

games = Game.select()
for g in games:
    names = g.name.name
    print(names)

>>> Multiset({'Sticks And Stones': 1, 'May Break Your Bones': 1 }) 

This also seems pretty ugly to me, I suppose there must be a better way?


Solution

  • It turns out the to_dict() method, well documented in PonyORM's API Reference, helps greatly with to-many relationships.

     for g in games:
          this_game = g.to_dict(
              with_collections=True,
              related_objects=True,
              exclude=['game_meta', 'statistics']
          )
    

    And then access the dict() entries like this: this_game['name']