我有一个包含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的新手,我在文档中找不到任何解决方案。
答案 0 :(得分:0)
如果您正在使用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()