Querying JSONB Postgres fields in SQLAlchemy
March 3, 2020
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()
