Include OneToMany relationship in query in peewee (Flask) Include OneToMany relationship in query in peewee (Flask) flask flask

Include OneToMany relationship in query in peewee (Flask)


This is the classic O(n) query problem for ORMs. The documentation goes into some detail on various ways to approach the problem.

For this case, you will probably want prefetch(). Instead of O(n) queries, it will execute O(k) queries, one for each table involved (so 2 in your case).

storages = Storage.select().order_by(Storage.name)drawers = Drawer.select().order_by(Drawer.name)query = prefetch(storages, drawers)

To serialize this, we'll iterate through the Storage objects returned by prefetch. The associated drawers will have been pre-populated using the Drawer.storage foreign key's related_name + '_prefetch' (drawers_prefetch):

accum = []for storage in query:    data = {'name': storage.name, 'description': storage.description}    data['drawers'] = [{'name': drawer.name}                       for drawer in storage.drawers_prefetch]    accum.append(data)

To make this even easier you can use the playhouse.shortcuts.model_to_dict helper:

accum = []for storage in query:    accum.append(model_to_dict(storage, backrefs=True, recurse=True))