Last Updated: February 25, 2016
· lukasz-madon

SQLAlchemy model to dictionary

I'm building an app with AngularJS + Flask on Heroku. I really love how extensible and powerful Flask is. Here is a small pice of code that I use to convert SQLAlchemy model to dictionary and then I serialise it to JSON.

def model_to_dict(inst, cls):
  Jsonify the sql alchemy query result. Skips attr starting with "_"
  convert = { "DATETIME": datetime.datetime.isoformat}
  d = dict()
  for c in cls.__table__.columns:
    v = getattr(inst,
    current_type = str(c.type)
    if current_type in convert.keys() and v is not None:
        d[] = convert[current_type](v)
        d[] = "Error:  Failed to covert using ", unicode(convert[c.type])
    elif v is None:
      d[] = unicode()
      d[] = v
  return d

Instead of using underscore for hiding fields you can write your own serializer e.g.