带连接的 Peewee 查询无法按预期工作
Peewee query with join doesn't work as expected
我是 peewee 的新手,目前正在尝试从普通 Python SQlite3 库迁移。
虽然我的代码生成了一个有效的 SQL 查询,return 使用 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'
Peewee 查询:
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
Return这个:
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 风格的名称。
我是 peewee 的新手,目前正在尝试从普通 Python SQlite3 库迁移。
虽然我的代码生成了一个有效的 SQL 查询,return 使用 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'
Peewee 查询:
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
Return这个:
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 风格的名称。