Using SQLAlchemy can easily read the data from the Python object in the form of a database (spit slot: To tell the truth, the form of the object is not much convenient, as I have directly read from the relational database dict form of data to use it handy, see my previous article http:// ZHENGXIAOYAO0716.LOFTER.COM/POST/1D6E9C56_93D6D00))
However, data in the form of objects is inconvenient for direct HTTP transmission, which is generally more convenient to convert to JSON. And if you directly dumps or jsonify the object from the database, you get an error. Google is actually a lot of solutions, those methods are very good, the solution is also more perfect. But I have to say it's a bit of a hassle. My approach may not be perfect, but most of the simple cases are enough to solve the problem.
First, add a method to the base of the data model (I don't know if that's the way to call it, but that's the class that inherits when you create a new data model class, my name is base):
[Python]View Plaincopyprint?
- def column_dict (self):
- Model_dict = Dict (self.__dict__)
- del model_dict[' _sa_instance_state ']
- return model_dict
- Base.column_dict = Column_dict
What's the way it's doing? First, copy the dictionary of the data object, and then remove the key as ' _sa_instance_state ' record, yes, in most cases it prevents us from dumps, jsonify steps. Note is the dict operation of the new copy, otherwise it will affect the database itself the foreign Key association is tragic ~
So suppose there is a model that inherits from the base, such as class User (Base): ..., we get an object of it, such as User = User.query.get (1), as long as the User.column_dict () It's good to be a dumps. If the user has a foreign key association, please do it yourself for ext in user.exts: ..., and then add each ext column_dict () to user_dict (user_dict = user.column_dict ()) because I'm lazy. ~ and in many cases it is not necessary to take out all the associated data ...
Well, that's it, a simple imperfect but very effective solution technique ~ ~ ~
How to easily get dict data and dumps into JSON when using SQLAlchemy