【问题标题】:Accessing values from one-to-many relationship in PonyORM在 PonyORM 中从一对多关系访问值
【发布时间】:2019-05-26 20:51:41
【问题描述】:

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

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 }) 

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

【问题讨论】:

  • games = select((g, g.name.names) for g in Game)[:] 我猜?

标签: ponyorm


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多