[英]SQLAlchemy method to get ORM object as dict?
Take the following code:采取以下代码:
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String
engine = create_engine('postgresql://postgres:password@localhost:5432/db', echo=True, echo_pool='debug')
Base = declarative_base()
class Item(Base):
__tablename__ = 'items'
id = Column(Integer, primary_key=True)
name = Column(String)
def __repr__(self):
return "<Item(id=%s, name='%s')>" % (self.id, self.name)
item = Item(name="computer")
Is there a way to get a python dict of the Item
with all its fields?有没有办法获得Item
的 python 字典及其所有字段? For example, I would like to get the following returned:例如,我想返回以下内容:
item.to_dict()
{"id": None, "name": "computer"}
Or do I have to write my own method to do that?还是我必须编写自己的方法来做到这一点?
Here would be one way to do it:这是一种方法:
class MyBase(Base):
__abstract__ = True
def to_dict(self):
return {field.name:getattr(self, field.name) for field in self.__table__.c}
class Item(MyBase):
# as before
# {'id': None, 'name': 'computer'}
Also, a lot of these usability simplifications can be found in: https://github.com/absent1706/sqlalchemy-mixins .此外,许多这些可用性简化可以在: https://github.com/absent1706/sqlalchemy-mixins中找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.