Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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?

like image 393
David542 Avatar asked Jul 21 '26 23:07

David542


1 Answers

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

item = Item(name="computer")
item.to_dict()
# {'id': None, 'name': 'computer'}

Also, a lot of these usability simplifications can be found in: https://github.com/absent1706/sqlalchemy-mixins.

like image 192
David542 Avatar answered Jul 24 '26 13:07

David542



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!