import psycopg2 import os pg = psycopg2.connect( dbname=os.getenv("POSTGRES_DB"), user=os.getenv("POSTGRES_USER"), password=os.getenv("POSTGRES_PASSWORD"), port=os.getenv("POSTGRES_PORT"), host=os.getenv("POSTGRES_HOST"), ) def get_chapters(ids): cur = pg.cursor() cur.execute( """ SELECT ch.id, ch.explanation FROM chapters ch WHERE ch.id = ANY (%s); """, (ids,), ) data = cur.fetchall() cur.close() chapters = list(map(lambda x: {"id": x[0], "explanation": x[1]}, data)) ordered_chapters = [] for id in ids: chapter = next( (ch for ch in chapters if ch["id"] == id), None, ) if chapter: ordered_chapters.append(chapter) return ordered_chapters