SQLAlchemy Convert to JSON format
SQLAlchemy queries the object into JSON format if the data model does not use foreign keys. You can then directly invoke the Dict method in object to convert the object to dict format, and then Json.dumps.
If the data model uses a foreign key, after calling the Dict method, there will be a "_sa_instance_state" key, whose value is an object, there are many configurable pairs of parameters for the foreign key:
backref:在一对多或多对一之间建立双向关系lazy:默认值是True,说明关联对象只有到真正访问的时候才会去查询数据库,比如有parent对象,只有知道访问parent.children的时候才做关联查询,这就是上面所说的在调用了dict后,对于的外键关联会生成一个关联表的查询object。
The need to format JSON for queries that have foreign keys can be implemented by the following code:
Import JSON class Complexencoder (JSON. Jsonencoder): def default (self, obj): If Isinstance (obj, datetime.datetime): Return Obj.strftime ('%y- %m-%d%h:%m:%s ') elif isinstance (obj, datetime.date): Return obj.strftime ('%y-%m-%d ') Else: Return JSON. Jsonencoder.default (self, obj) def obj_to_json (obj_list): off = [q.__dict__ for q in obj_list] for OBJS, instance I n Zip (out, obj_list): for obj in Objs.values (): If callable (obj): for name in Obj.mapper. Relationships.keys (): TMP = GetAttr (instance, name). __dict__ If "_sa_instance_state" In Tmp.keys (): Tmp.pop ("_sa_instance_state") Tmp.pop ("id") Objs.update (TMP) Objs.pop (name) if "_sa_instance_state" in Objs.keys (): OBJS.P OP ("_sa_instance_state") return out Def Query_result_json (query_result): "" "CoNvert query result to JSON format "" "If Isinstance (Query_result, list): result = Obj_to_json (Query_result) Elif getattr (Query_result, ' __dict__ ', '): result = Obj_to_json ([Query_result]) Else:result = {' Resul T ': Query_result} return Json.dumps (result, Cls=complexencoder) Import JSON class Complexencoder (JSON. Jsonencoder): def default (self, obj): If Isinstance (obj, datetime.datetime): Return Obj.strftime ('%y- %m-%d%h:%m:%s ') elif isinstance (obj, datetime.date): Return obj.strftime ('%y-%m-%d ') Else: Return JSON. Jsonencoder.default (self, obj) def obj_to_json (obj_list): off = [q.__dict__ for q in obj_list] for OBJS, instance I n Zip (out, obj_list): for obj in Objs.values (): If callable (obj): for name in Obj.mapper. Relationships.keys (): TMP = GetAttr (instance, name). __dict__ If "_sa_instance_state" In Tmp.keys (): Tmp.pop ("_sa_instance_state") Tmp.pop ("id") objs.update (TMP) Objs.pop (name) if "_sa_instance_state" in Objs.keys (): Objs.pop ("_sa_instance_state" Return out Def Query_result_json (query_result): "" "" "" "" Convert query result to JSON format "" If Isinstanc E (Query_result, list): result = Obj_to_json (query_result) elif getattr (Query_result, ' __dict__ ', '): Res Ult = Obj_to_json ([Query_result]) Else:result = {' result ': Query_result} return Json.dumps (result, Cls=compl Exencoder)
Python sqlalchemy JSON