python - 将 SQLAlchemy 对象转换为 Python 字典的快速方法

标签 python sqlalchemy flask-sqlalchemy

我有一个返回学生对象列表的查询:

query = db.session.query(Student).filter(Student.is_deleted == false())
query = query.options(joinedload('project'))
query = query.options(joinedload('image'))
query = query.options(joinedload('student_locator_map'))
query = query.options(subqueryload('attached_addresses'))
query = query.options(subqueryload('student_meta'))
query = query.order_by(Student.student_last_name, Student.student_first_name,
                           Student.student_middle_name, Student.student_grade, Student.student_id)
query = query.filter(filter_column == field_value)
students = query.all()

查询本身并不需要太多时间。问题是将所有这些对象(可能超过 5000 个)转换为 Python 字典。处理这么多对象需要一分多钟的时间。目前,代码循环遍历对象并使用 to_dict() 进行转换。我也尝试过 _dict__ ,它要快得多,但这似乎并不能转换所有关系对象。

如何快速转换所有这些 Student 对象和相关对象?

最佳答案

也许这会对你有所帮助......

from collections import defaultdict

def query_to_dict(student_results):
   result = defaultdict(list)
   for obj in student_results:
      instance = inspect(obj)
      for key, x in instance.attrs.items():
         result[key].append(x.value)
   return result

output = query_to_dict(students)

关于python - 将 SQLAlchemy 对象转换为 Python 字典的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49414667/

相关文章:

python - Pyomo "data = None"输出错误

python - 为什么删除列时 Flask-migrate 无法升级

mysql - (MySQLdb._exceptions.OperationalError) (1045, "Access denied for user ' DELL' @'localhost' (使用密码 : NO)")

python - 无法在 Google Cloud Platform 上的保留静态地址上查看 Flask 应用程序

python - Flask:渲染模板并填充 HTML 表

python - 遍历数据框并选择空值

python - 使用全局变量的 WebSocket 线程

python - 在Python中的virtualenv中安装statsmodels时出现PermissionError

python - Flask-SQLAlchemy 查询多对多

python - Flask SQLAlchemy NOT NULL 约束在主键上失败