ponyorm - 在 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 })
这对我来说似乎也很丑陋,我想一定有更好的方法吗?
解决方案
事实证明,该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']
推荐阅读
- sql - 在 SQL 查询中计算计数并在同一查询中比较它们
- c# - Web Api OData v4 不再在 Swagger UI 中显示控制器
- vba - 检查并修复 excel 中与其他工作表的断开链接
- jenkins - 禁用 Jenkins 变量扩展
- python - 使用 selenium python 滚动并查找元素
- angular - 基于可变段的角度路径子项
- r - 将显示在 R Studio 控制台中的 pdf 转换为文本的结果以 .txt 格式保存
- php - 这个 $_SERVER['REQUEST_METHOD'] === 'POST' 做什么?
- python - Python 下对角线和上对角线中的矩阵数据
- mysql - INT(1)和INT(11)有什么区别,其中一个存储值99999