Back in the days I recall there was some plug-in to query Pivot tables in postgres, but it was such a pain to use that a two step approach (query the column names, and then generate a second query based on these column names) with Python/SQLAlchemy glue code was easier and possibly even more performant. I hope the situation has improved, as indeed pivot tables are so useful