Search code examples
pythonsqlasyncpg

How can I return multiple rows in AsyncPG?


Let's say I have a table with the following format:

favoritefood favoritedrink
pizza water
ice cream orange juice
pizza milk

How would I return both rows with pizza as the favorite food with Python?

I have fetchrow implemented for other functions, but it only works for one row, of course.

Ideally, they would be sorted into dictionaries (ex: {favoritefood: pizza, favoritedrink: water)


Solution

  • To obtain multiple rows, use fetch().

    The returned Record instances are already dict-like, but if you really want regular Python dicts, simply convert the result data afterward:

    rows = await connection.fetch("SELECT * FROM table WHERE favoritefood = $1", 'pizza')
    data = [dict(row) for row in rows]