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



我有这个查询,它返回学生对象列表:

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__它的速度要快得多,但这似乎并没有转换所有关系对象。

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

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

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)
query = query.options(joinedload('attached_addresses').joinedload('address'))

通过将地址 joinedload 链接到attached_addresses我能够显着加快查询速度。

我对为什么会这样的理解:

未使用初始查询加载地址对象。每次迭代通过循环,db 都会被命中以检索 Address 对象。使用联接加载时,地址对象现在在初始查询时加载。

感谢Corley Brigman的帮助。

最新更新