Sunday, 15 August 2010

python - How to create sqlalchemy to json -



python - How to create sqlalchemy to json -

i have sqlalchemy result

labels = session.query( labelsdata, labelsdata.id, labelsdata.name, labelsdata.color ).filter(labelsdata.deleted==false).all()

and want convert result json, how can it?

it looks labelsdata object sqlalchemy model. need serialize before dumping json. here's short illustration extracts columns labelsdata object , converts results of query json:

from json import dumps sqlalchemy.orm import class_mapper def serialize(model): """transforms model dictionary can dumped json.""" # first names of columns on model columns = [c.key c in class_mapper(model.__class__).columns] # homecoming values in dict homecoming dict((c, getattr(model, c)) c in columns) # can utilize particular illustration serialized_labels = [ serialize(label) label in session.query(labelsdata).filter(labelsdata.deleted == false) ] your_json = dumps(serialized_labels)

python json sqlalchemy

No comments:

Post a Comment