Search code examples
pythonpeewee

How to add a list of joined data in peewee?


I have 2 tables: dungeons and monsters. In dungeons I have 2 records and 4 records in monsters. Each monster has a foreing key linking it to a certain dungeon.

I need to get a list of dungeons so each dungeon will have a list of it's own with all monsters that live in it.

I try to do this:

dungeons = list(Dungeons.select().join(Monsters))

It returns 4 entries: 1. dungeon 1 monster 1 2. dungeon 1 monster 2 3. dungeon 2 monster 3 4. dungeon 2 monster 4

But I need to have something like this: 1. dungeon 1 [monster1, monster2] 2. dungeon 2 [monster3, monster4]


Solution

  • There's a more efficient way: use prefetch(). It is documented in the "Avoiding N+1 queries" section.

    query = prefetch(Dungeon.select(), Monster.select())
    for dungeon in query:
        print dungeon.name
        for monster in dungeon.monsters_prefetch:  # This is a list of monsters
            print '    *', monster.name