【问题标题】:Adding records with SQLAlchemy ORM使用 SQLAlchemy ORM 添加记录
【发布时间】:2018-04-17 13:47:48
【问题描述】:

我有一个包含 2 列的表:student_ids 和 teacher_ids。我想获取一个 student_id 列表,假设 student_ids = [1,2,3,4,5,6] 和一个教师 id:teacher_id = 2 并添加它们到我的桌子上。最好的选择是什么?我必须创建一个对象列表:

obj1.student_id = 1

obj1.teacher_id = 2

obj2.student_id = 2

obj2.teacher_id = 2

等等……

然后 add_all()

有没有更好的方法?我是 sqlalchemy 的新手,在文档中没有找到任何解决方案。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    如果你使用 SQLAlchemy ORM,你可以使用 Python 的itertools.product 来简化赋值:

    from itertools import product
    
    # assuming teacher_obj, student_obj, and db is already created here
    teacher_ids = [1, 2]      # just as an example
    student_ids = [1, 2, 3, 4, 5, 6]    # ditto
    for tid, sid in product(teacher_ids, student_ids):
        teacher_obj.id = tid
        student_obj.id = sid
    
    db.session.commit()
    

    如果您使用的是 SQLAlchemy Core,则可以使用连接的 execute 方法:

    conn = engine.connect()
    
    ins = users.insert()
    conn.execute(
        users.insert(),
        [{"teacher_id": 1, "student_id": 2},
         {"teacher_id": 1, "student_id": 3}])
    

    当然,前提是您已经完成了必要的设置,例如:

    from sqlalchemy import create_engine, Column, Integer, Table, MetaData
    
    engine = create_engine('sqlite:///:memory:', echo=True)
    metadata = MetaData()
    
    users = Table('users', metadata,
                  Column('teacher_id', Integer),
                  Column('student_id', Integer))
    
    metadata.create_all(engine)
    conn = engine.connect()
    

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 2015-04-16
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多