• 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根据模型类的定义自动识别和映射表结构,并生成适当的联表查询语句。

  • 相关阅读:
    Python机器学习、深度学习提升气象、海洋、水文领域实践应用
    测试基础知识面试考点
    数据库事务
    径向基函数RBF神经网络相关函数设置
    事件对象学习
    Lnmp的搭建
    河南灵活用工系统开发|灵活用工模式适合电商行业吗?
    Layui实现之登陆页面&&实现扩展模块
    Xilinx AXI USB2.0 Device IP 手册阅读笔记
    Electron基本介绍
  • 原文地址:https://blog.csdn.net/qq_31455841/article/details/134313847