• sqlalchemy-orm联表查询指定字段


    1. 联表查询全部字段
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    
    # 创建数据库连接
    engine = create_engine('mysql://username:password@localhost/database_name')
    Session = sessionmaker(bind=engine)
    session = Session()
    
    # 联表查询
    query = session.query(ANNInspectionBatchTaskModel, ANNDistributionBatchTaskModel).\
        filter(ANNInspectionBatchTaskModel.id == ANNDistributionBatchModel.task_id)
    
    # 获取查询结果
    results = query.all()
    
    # 打印查询结果
    for result in results:
        ann_inspection_task = result[0]
        ann_distribution_task = result[1]
        print(ann_inspection_task.id, ann_inspection_task.other_field1, ann_inspection_task.other_field2,
              ann_distribution_task.id, ann_distribution_task.task_id, ann_distribution_task.other_field3)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在上面的代码中,首先创建数据库连接并创建一个Session对象。然后使用session.query()方法指定要查询的两个模型类,并使用filter()方法指定关联条件。最后使用all()方法获取查询结果,并通过遍历结果获得每一行的数据。

    2. 联表查询指定字段
    # 联表查询,并指定需要的字段
    query = session.query(BatchTaskModel.id,
                          BatchTaskModel.other_field1,
                          DistributionTaskModel.task_id,
                          DistributionTaskModel.other_field3
                         ).(ANNInspectionBatchTaskModel.id == ANNDistributionBatchTaskModel.task_id)
    
    # 获取查询结果
    results = query.all()
    
    # 打印查询结果
    for result in results:
        ann_inspection_id = result[0]
        ann_inspection_other_field1 = result[1]
        ann_distribution_task_id = result[2]
        ann_distribution_other_field3 = result[3]
        print(ann_inspection_id,_inspection_other_field1, ann_distribution_task_id, ann_distribution_other_field3)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在上述代码中,session.query() 方法中指定了需要的字段,然后通过遍历查询,可以获取每一行中指定字段的值。

    实际上,当你在 session.query() 方法中指定了需要的字段,SQLAlchemy 会自动根据模型类的定义和关联条件来生成适当的联表查询语句,无需显式指定表名称。

    在上述代码中,我们直接使用了结果对象的属性来获取指定字段的值,而无需指定表名称。SQLAlchemy ORM根据模型类的定义自动识别和映射表结构,并生成适当的联表查询语句。

  • 相关阅读:
    【LeetCode】LeetCode 106.从中序与后序遍历序列构造二叉树
    appinventor多个拓展导入导致编译出错:
    竞赛选题 深度学习 机器视觉 人脸识别系统 - opencv python
    【STM32】标准库-LTDC-DMA2D
    2023 家电行业品牌社媒营销洞察报告
    不愧是阿里架构师,吐血更新笔记,这应该是对“Spring家族”最完美的诠释了!
    数据库驱动和JDBC
    学习java的第十八天。。。(子类)
    【PickerView案例14-复习第一天内容 Objective-C语言】
    PC_算计机性能指标
  • 原文地址:https://blog.csdn.net/qq_31455841/article/details/134313847