darkphoenix
darkphoenix

Reputation: 2167

How do I use PostgreSQL's jsonb_to_record in SQLAlchemy?

PostgreSQL has functions like jsonb_to_record or jsonb_populate_record which allow you convert data stored in a JSONB column to separate columns. however, I'm using SQLAlchemy and jsonb_to_record requires a predefined structure for the output (see example below from the PostgreSQL docs)

select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}') as x(a int, b text, d text)

Is there a way to use these functions from SQLAlchemy?

Upvotes: 2

Views: 721

Answers (1)

Thijs D
Thijs D

Reputation: 782

you can use any postgres function in SQLAlchemy with func like so:

from SQLAlchemy import func
session.query(func.json_to_record(Model.jsonb_field))

Do note that set-returning functions are a bit of a pain to deal with with SQLAlchemy, but if you want you can get it to work.

Upvotes: 2

Related Questions