简体   繁体   中英

Peewee: condensing two select queries into a join

So I'm trying to turn my double query into a join, here's what my peewee select queries look like:

for app in AppInfo.select().limit(5):
    for event in EventHistory.select().where(EventHistory.appname==app.appname):
        print event

So this is what I tried:

for app in AppInfo.select().join(EventHistory).where(EventHistory.appname==AppInfo.appname).limit(10):
    print app

But eh... well seems like I'm doing something very wrong in here.

Here are my models:

class BaseModel(Model):
    class Meta:
        database = db

class AppInfo(BaseModel):
    appname = TextField()
    appowner = TextField()

class EventHistory(BaseModel):
    appname = TextField(primary_key=True)
    time = DateTimeField()
    message = TextField()

Check out the docs on N+1: http://docs.peewee-orm.com/en/latest/peewee/querying.html#avoiding-n-1-queries

It doesn't appear you have an actual foreign key between AppInfo and EventHistory, which should be amended:

class EventHistory(BaseModel):
    appname = ForeignKeyField(
        EventHistory, 
        primary_key=True, 
        related_name='event_history',
        to_field='appname')
    # other fields ...

Once you have that fixed up, you can write:

query = prefetch(AppInfo, EventHistory)
for app in query:
    print app
    for event in app.event_history_prefetch:
        print event

Similarly you can use aggregate_rows():

query = AppInfo.select(AppInfo, EventHistory).join(EventHistory).aggregate_rows()
for app in query:
    print app
    for event in app.event_history:
        print event

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