Querying JSONB Postgres fields in SQLAlchemy

Below is SQLAlchemy model

class Product(Base):
  __tablename__ = 'products'
  id = Column(UUID(as_uuid=True), primary_key=True, server_default=text('uuid_generate_v4()'))
  title = Column(String(64), nullable=False)
  data = Column(JSONB)

Add data to the model

sample_data = {
'photos': [{ 'title': 'pic1', link': 'images/image1.png', 'active': true}, { 'title': 'pic2', link': 'images/image2.png', 'active': false}, { 'title': 'pic3', 'link': 'images/image3.png', 'active': true}]
}
session.add(Product(title='A new product', data=sample_data))
session.commit()

Filter using the query as below.

# compare boolean
active_photos = session.query(Product).filter(Product.photos['active'] == cast(True, JSON)).all()

# compare text
pic_1_photos= session.query(Product).filter(Product.photos['pic'].astext == 'pic1').all()

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image