Last Updated: February 25, 2016
·
8.106K
· 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:
    if c.name.startswith("_"):
      continue
    v = getattr(inst, c.name)
    current_type = str(c.type)
    if current_type in convert.keys() and v is not None:
      try:
        d[c.name] = convert[current_type](v)
      except:
        d[c.name] = "Error:  Failed to covert using ", unicode(convert[c.type])
    elif v is None:
      d[c.name] = unicode()
    else:
      d[c.name] = v
  return d

Instead of using underscore for hiding fields you can write your own serializer e.g. https://github.com/mattupstate/overholt/blob/master/overholt/products/models.py