简体   繁体   中英

Peewee query with join doesn't work as expected

I'm new to peewee and currently trying to migrate from normal Python SQlite3 library.

While my code generate a valid SQL query that return result as expected using a SQlite DB browser, trying to get the value of a field return AttributeError: x object has no attribute y .

Model:

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 Query:

data = TableHistory.select(
        TableShows.title,
        TableHistory.sonarr_series_id
    ).join(
        TableShows
    ).order_by(
        TableShows.title.asc()
    )

Resulting SQL query:

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

Resulting dicts():

{'title': u'Test title', 'sonarr_series_id': 1}

Why does running this:

for item in data:
    print item.title

Return this:

AttributeError: 'TableHistory' object has no attribute 'title'

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

You access the data via item.sonarr_series_id.title

You might consider naming your fields something a bit more pythonic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM