This article describes how to write a Python script to convert a sqlAlchemy object to dict. It mainly builds a conversion method based on the Python model class, if you want to write a web application using sqlAlchemy, you may often use json for communication. dict is the closest object to json, sometimes it is more convenient to operate dict than to operate ORM objects. after all, you don't have to worry about the database session status.
Assume that there is a post table in the database, one of the methods is
p = session.query(Post).first()p.__dict__
However, since p is an object of sqlAlchemy, we do not need to pay attention to other attributes in p. _ dict _, such as _ sa_instance.
Then we can add a method to the base class of the model, assuming that the original method in models. py is as follows:
Base = sqlalchemy.ext.declarative.declarative_base()class Post(Base): __tablename__ = 'post' id = Column(Integer, primary_key=True) title = Column(String)
Then we can add a to_dict () method to the Base class.
def to_dict(self): return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}Base.to_dict = to_dict
In this way, you can
p = session.query(Post).first()p.to_dict()
Of course, if the model is not bound to the table, there is no _ table _ information in the model, which may cause problems, but I think this is the most convenient at present.