'sqlalchemy return constant dict in select
I am using sqlalchemy with MySql. I need to return a dict in select. Adding that dict value to fetched data is not an option. Is there any way in sqlalchemy or MySQL by which I can add JSON here
case(
[
(
and_(
SomeTable.somefield.notin_(
constants.SLUGS),
OtherTable.otherfield == 1
),
[{
'label': 'Success',
'value': 'True'
}]
)
],
else_=False
).label('status')
Solution 1:[1]
Casting to JSON ought to work for MySQL (but not for Mariadb):
>>> import sqlalchemy as sa
>>>
>>> engine = sa.create_engine('mysql:///test', echo=True, future=True)
>>> with engine.connect() as conn:
... res = conn.execute(sa.select(sa.case([(True, sa.cast([{'label': 'success', 'value': True}], sa.JSON))], else_=False).label('status')))
... print(res)
[{"label": "success", "value": true}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | snakecharmerb |