Deserializing JSON in SQLAlchemy when using raw SQL

后端 未结 1 1918
失恋的感觉
失恋的感觉 2020-12-12 03:54

I have a table with JSON stored in a text column:

import json
from sqlalchemy import create_engine, Column, text, Integer, TEXT, TypeDecorator
from sqlalchem         


        
相关标签:
1条回答
  • 2020-12-12 04:43

    You can tell TextClause (produced by text()) the column types using .columns():

    from sqlalchemy import inspect
    
    session = Session()
    stmt = text('select * from t').columns(*inspect(T).columns)
    t = session.query(T).from_statement(stmt).first()
    assert type(t.attrs) == dict, repr(t.attrs)
    

    Or, for SQLAlchemy<0.9, use the typemap argument:

    from sqlalchemy import inspect
    
    session = Session()
    typemap = {c.name: c.type for c in inspect(T).columns}
    stmt = text('select * from t', typemap=typemap)
    t = session.query(T).from_statement(stmt).first()
    assert type(t.attrs) == dict, repr(t.attrs)
    
    0 讨论(0)
提交回复
热议问题