sqlAlchemy中的对象转换为dict
假设数据库里有一张post表,其中一种方法就是
p = session.query(Post).first()
p.__dict__
但由于p是sqlAlchemy的对象,所以p.__dict__
中会有一些其他的属性比如_sa_instance
这种我们不需要关注的
那么我们可以给model的基类加一个方法,假设models.py
中原来是这样
Base = sqlalchemy.ext.declarative.declarative_base()
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
title = Column(String)
那么我们可以加一个to_dict()
方法到Base
类中
def to_dict(self):
return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}
Base.to_dict = to_dict
这样就可以
p = session.query(Post).first()
p.to_dict()
当然,如果model没有和table绑定的话model里是没有__table__
的信息的,可能也会出问题,不过我目前觉得这样最方便了
- 新浪微博
- 微信
赞 | 2收藏 | 2
你可能感兴趣的
- SICP Python 描述 2.5 面向对象编程飞龙sicppython
- Flask-SQLAlchemy 学习总结MouseHousepythonflask
- SQLAlchemy系列之一杭州丶付帅帅sqlalchemypython
- 5.ORM与SQLAlchemy (1) - 建立第一个模型Harpsichord1207pythonflask
- 流畅的 Python - 2. 字典与集合Xinnaypython
- [零基础学python]不要红头文件(2)老齐Py零基础python
- Python序列化模型数据为JSON我勒个去ormpython
- [零基础学Python]dict()的操作方法老齐Pypython
3 条评论
默认排序时间排序
浮生若梦的编程 · 2016年11月11日
DateTime 之类的,可能还需要转换下
def to_dict(self):
def convert_datetime(value):
if value:
return value.strftime("%Y-%m-%d %H:%M:%S")
else:
return ""
for col in self.__table__.columns:
if isinstance(col.type, DateTime):
value = convert_datetime(getattr(self, col.name))
elif isinstance(col.type, Numeric):
value = float(getattr(self, col.name))
else:
value = getattr(self, col.name)
yield (col.name, value)
赞 +1 回复
浮生若梦的编程 · 2016年11月11日
def to_json(self):
d = dict(self.__todict__())
return json.dumps(d)
赞 回复
Recoding · 2017年02月20日
还是推荐额外写方法来装换,不然每个model都有添加方法
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)
来自stackoverflow 具体链接不记得
赞 回复
发布评论