簡體   English   中英

SQLAlchemy 方法得到 ORM object 作為字典?

[英]SQLAlchemy method to get ORM object as dict?

采取以下代碼:

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")

有沒有辦法獲得Item的 python 字典及其所有字段? 例如,我想返回以下內容:

item.to_dict()
{"id": None, "name": "computer"}

還是我必須編寫自己的方法來做到這一點?

這是一種方法:

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'}

此外,許多這些可用性簡化可以在: https://github.com/absent1706/sqlalchemy-mixins中找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM