python - 带有连接的 Peewee 查询无法按预期工作
问题描述
我是 peewee 的新手,目前正在尝试从普通的 Python SQlite3 库迁移。
虽然我的代码生成了一个有效的 SQL 查询,该查询使用 SQlite DB 浏览器按预期返回结果,但试图获取字段 return 的值AttributeError: x object has no attribute y
。
模型:
class TableShows(BaseModel):
sonarr_series_id = IntegerField(column_name='sonarrSeriesId', unique=True)
title = TextField()
class Meta:
table_name = 'table_shows'
class TableHistory(BaseModel):
sonarr_series_id = ForeignKeyField(TableShows, field='sonarr_series_id', column_name='sonarrSeriesId')
class Meta:
table_name = 'table_history'
皮威查询:
data = TableHistory.select(
TableShows.title,
TableHistory.sonarr_series_id
).join(
TableShows
).order_by(
TableShows.title.asc()
)
生成的 SQL 查询:
SELECT "t1"."title", "t2"."sonarrSeriesId"
FROM "table_history" AS "t2"
INNER JOIN "table_shows" AS "t1" ON ("t2"."sonarrSeriesId" = "t1"."sonarrSeriesId")
ORDER BY "t1"."title" ASC
结果字典():
{'title': u'Test title', 'sonarr_series_id': 1}
为什么运行这个:
for item in data:
print item.title
返回这个:
AttributeError: 'TableHistory' object has no attribute 'title'
解决方案
http://docs.peewee-orm.com/en/latest/peewee/relationships.html#selecting-from-multiple-sources
您通过 item.sonarr_series_id.title 访问数据
您可能会考虑将您的字段命名为更具 Python 风格的名称。
推荐阅读
- gradle - Gradle 是否提供了一种添加任务而不将其包含在构建脚本中的方法?
- vb.net - 如何在 vb.net 中的图片框上绘制
- javascript - 使用带有 chart.js 和烧瓶的多个图表时,图表在缩放时变化不同
- scala - 为什么 groupBy 的签名只包含一个泛型?
- python - 如何模拟类函数的返回值
- java - JavaFX - 如果上面有节点,如何不显示父级的上下文菜单
- swift - 如何禁用 Swift Playground 实时取景窗口
- c# - 将 appsettings.json 读入定义了接口的对象中
- excel - Power Query:(文件夹中的数据)新的 CSV,其中添加的列替换了文件夹中其他 csv 的最后一列
- unity3d - unity - 显示箭头上的模拟值