This article mainly introduced the writing Python script to convert the SQLAlchemy object to the Dict tutorial, mainly based on the Python model class constructs a transformation method, needs the friend to be possible to refer to under
When using SQLAlchemy to write Web applications, often use JSON to communicate, with JSON the closest object is dict, sometimes operation Dict will be more convenient than the operation of ORM objects, after all, do not have to manage the state of database session.
Suppose there is a post table in the database, one of the methods is
?
1 2 |
p = session.query (Post). A () p.__dict__ |
But since p is a SQLAlchemy object, there are some other attributes in p.__dict__ such as _sa_instance that we don't need to focus on.
So we can add a method to the model's base class, assuming that it's the same in models.py.
?
1 2 3 4 5 6 |
Base = Sqlalchemy.ext.declarative.declarative_base () class Post (base): __tablename__ = ' Post ' id = Column (Integer, Prima Ry_key=true) title = Column (String) |
So we can add a to_dict () method to the base class
?
1 2 3 4 |
def to_dict (self): return {c.name:getattr (self, c.name, None) for C in self.__table__.columns} base.to_dict = To_dict |
So that we can
?
1 2 |
p = session.query (Post). A () p.to_dict () |
Of course, if model does not and table binding words model is no __table__ information, may also have problems, but I think this is the most convenient