首页 > 解决方案 > 在 PonyORM 中从一对多关系访问值

问题描述

对于游戏数据库,其中一个游戏被不同的用户称为不同的名称,我有两个表,设置为一对多:

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

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

如何访问特定游戏的名称?当我这样做时,它们以“Multiset”的形式返回,(我认为)是一个特殊的 Counter 对象:

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

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

这对我来说似乎也很丑陋,我想一定有更好的方法吗?

标签: ponyorm

解决方案


事实证明,该to_dict()方法在 PonyORM 的API Reference中有详细记录,对多对关系有很大帮助。

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

然后像这样访问 dict() 条目:this_game['name']


推荐阅读