Compile a Python script to convert a sqlAlchemy object to a dict tutorial, pythonsqlalchemy
When using sqlAlchemy to write a web application, it often uses json for communication. The object closest to json is dict. 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.