bulk_save_objects()更新问题

时间:2018-05-14 08:02:32

标签: python sql-server sqlalchemy bulk

我将使用bulk_save_objects()插入/更新对象。

插入没问题,但是当要进行更新时,它会尝试更新显然尚未更改的主键。

实体:

class MyObject(object):

    def __init__(self, id: int, f1: int, f2: int):
        self.id = id
        self.f1 = f1
        self.f2 = f2

映射:

my_table = Table('MyObject', metadata,
                 Column('Id', Integer, primary_key=True, autoincrement=True),
                 Column('F1', Integer),
                 Column('F2', Integer))

mapper(MyObject, my_table,
       properties={
           'id': my_table.c.Id,
           'f1': my_table.c.F1,
           'f2': my_table.c.F2
       })    

回购:

def save_my_objects(self, my_objects: List[MyObject]):
    self.session.bulk_save_objects(my_objects, return_defaults=True)
    self.session.commit()

逻辑:

my_objects = list()
my_objects.append(MyObject(None, 1, 2))

Repo.save_my_objects(my_objects)

my_objects[0].f1 = 15
Repo.save_my_objects(my_objects)  # Cannot update identity column 'Id'

0 个答案:

没有答案