How to compile a Python script to convert a sqlAlchemy object to dict
This article mainly introduces how to compile a Python script to convert the sqlAlchemy object to dict. It mainly constructs a conversion method based on the Python model class. For more information, see
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
?
1 2 |
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:
?
1 2 3 4 5 6 |
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.
?
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 |
In this way, you can
?
1 2 |
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.