python sqlalchemy的对象转换成dict

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python sqlalchemy的对象转换成dict相关的知识,希望对你有一定的参考价值。

from json import dumps
from sqlalchemy.orm import class_mapper

def serialize(model):
  """Transforms a model into a dictionary which can be dumped to JSON."""
  # first we get the names of all the columns on your model
  columns = [c.key for c in class_mapper(model.__class__).columns]
  # then we return their values in a dict
  return dict((c, getattr(model, c)) for c in columns)

# we can then use this for your particular example
serialized_labels = [
  serialize(label)
  for label in session.query(LabelsData).filter(LabelsData.deleted == False)
]
your_json = dumps(serialized_labels)
class User:
   def as_dict(self):
       return {c.name: getattr(self, c.name) for c in self.__table__.columns}

以上是关于python sqlalchemy的对象转换成dict的主要内容,如果未能解决你的问题,请参考以下文章

SQLAlchemy框架用法详解

把SQLAlchemy查询对象转换成字典使用

SQLALchemy之介绍,基本使用

SQLALchemy之介绍,基本使用

Python Sqlalchemy

ORM框架之SQLALchemy