编辑2:
class MethodCall(Base):
__tablename__ = 'methodCall'
id = Column(Integer, primary_key=True)
name = Column(String( 255 ), unique = True)
actions = relationship("Action")
def test_bulk_insert():
ses = DBSession()
mc = MethodCall()
a1 = Action()
a2 = Action()
a1.lfn = getFile(ses, 'toto')
a2.lfn = getFile(ses, 'toto')
mc.actions.append(a1)
mc.actions.append(a2)
编辑: 现在我有两个关系表:
class Action(Base):
__tablename__ = 'action'
id = Column(Integer, primary_key=True)
file_id = Column(Integer, ForeignKey('file.id'))
lfn = relationship("File")
methodCall_id = Column(Integer, ForeignKey('methodCall.id'))
class File(Base):
__tablename__ = 'file'
id = Column(Integer, primary_key=True)
name = Column(String( 255 ), unique = True)
当我插入两个这样的动作时:
a1 = Action()
a2 = Action()
a1.lfn = getFile(ses, 'toto')
a2.lfn = getFile(ses, 'toto')
ses.bulk_save_objects([a1,a2])
def getFile(session,n):
instance = session.query( File ).filter_by( name = n ).first()
if not instance:
instance = File( name=n )
session.add( instance )
session.commit()
return instance
未设置表操作中的file_id,它为null。 我该怎么办?
插入行时,SQLALchemy有点问题。
我有一个表格文件:
class File(Base): __tablename__ = 'file' id = Column(Integer, primary_key=True,autoincrement=True)
当我插入两个这样的文件时:
f1 = File( id = 1 ) f2 = File( id =2 ) session.add(f1) session.add(f2) session.commit()
它是一个批量插入:
2015-06-16 11:27:57,057 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2015-06-16 11:27:57,058 INFO sqlalchemy.engine.base.Engine INSERT INTO file (id) VALUES (%s) 2015-06-16 11:27:57,058 INFO sqlalchemy.engine.base.Engine ((1,), (2,)) 2015-06-16 11:27:57,060 INFO sqlalchemy.engine.base.Engine COMMIT
但是当我没有精确的id时,插入是一个接一个:
f1 = File( ) f2 = File( ) session.add(f1) session.add(f2) session.commit() 2015-06-16 11:28:46,648 INFO sqlalchemy.engine.base.Engine INSERT INTO file () VALUES () 2015-06-16 11:28:46,649 INFO sqlalchemy.engine.base.Engine () 2015-06-16 11:28:46,654 INFO sqlalchemy.engine.base.Engine INSERT INTO file () VALUES () 2015-06-16 11:28:46,654 INFO sqlalchemy.engine.base.Engine () 2015-06-16 11:28:46,655 INFO sqlalchemy.engine.base.Engine COMMIT
当我没有精确的ID来批量插入时,有什么办法吗? 自动递增?
谢谢