首页 > 解决方案 > 带有连接的 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'

标签: pythonpython-2.7peewee

解决方案


http://docs.peewee-orm.com/en/latest/peewee/relationships.html#selecting-from-multiple-sources

您通过 item.sonarr_series_id.title 访问数据

您可能会考虑将您的字段命名为更具 Python 风格的名称。


推荐阅读