SQLALchemy session.merge不起作用

时间:2016-03-26 13:34:53

标签: python sqlalchemy flask-sqlalchemy

AFAIK合并执行和insert or update所以我正在做的事情非常简单。 集线器和标签之间存在1到N的关系。 因此,当我尝试在标记和集线器上进行合并时,集线器顺利运行并从DB加载现有集线器并进行更新,但在执行db.session.merge(nuevo_tag)时抛出异常,因为在幕后尝试进行插入,即使标签以前存在。 我做错了什么?

nuevo_hub = Hub(guid_hub,name,location,comments,id_project,creado_en,actualizado_en)
merged_hub = db.session.merge(nuevo_hub)
#db.session.commit() # If I use this line tags perform an insert.
nuevo_tag = Tag(guid_tag,project,merged_hub,TYPE_HUB,creado_en,actualizado_en)
merged_tag = db.session.merge(nuevo_tag)
db.session.commit()

如果我删除db.session.commit(),则会显示其他错误:

  

sqlalchemy.orm.exc.FlushError:新实例   身份密钥(,   (b'\ x11 \ x0e \ x84 \ x00 \ xe2 \ x9b \ x11 \ xd4 \ xa7 \ x16DfUD \ x00 \ r',))冲突   持久化实例

class Item(db.Model):
    __tablename__ = "items"
    # id_item     = db.Column(db.Integer, autoincrement=True, primary_key=True)
    guid_item   = db.Column(db.BINARY(16), primary_key=True)
    id_project  = db.Column(db.Integer,db.ForeignKey("projects.id_project"))
    type        = db.Column(db.Integer)
    name        = db.Column(db.String(50), nullable=False, index= True)
    created_at  = db.Column(db.DateTime)
    updated_at  = db.Column(db.DateTime)
    __mapper_args__ = {
        'polymorphic_identity': 'items',
        'polymorphic_on':type,
        'with_polymorphic':'*'
    }
    __table_args__ = (
                        db.UniqueConstraint('name', 'id_project', name='_unique_name_project'),
                     )

    def __init__(self,creado_en=None):
        self.created_at = creado_en
        self.updated_at = creado_en


class Hub(Item):
    __tablename__ = "hubs"
    __mapper_args__ = {
        'polymorphic_identity': TYPE_HUB,
        'with_polymorphic':'*'
    }
    guid_hub = db.Column(db.BINARY(16), db.ForeignKey(Item.guid_item), primary_key=True)
    location = db.Column(db.String(50))
    comments = db.Column(db.String(128))

    def __init__(self, guid_hub=None, nombre=None, location=None,comments=None, id_project=None, creado_en=None, actualizado_en=None):
        self.type = TYPE_HUB
        self.guid_item = guid_hub
        self.guid_hub = guid_hub
        self.name = nombre
        self.id_project = id_project
        self.location = location
        self.comments = comments
        self.created_at = creado_en
        self.updated_at = actualizado_en


class Tag(db.Model):
    __tablename__ = "tags"
    guid_tag      = db.Column(db.BINARY(16), primary_key=True)
    id_project  = db.Column(db.Integer,db.ForeignKey("projects.id_project"))
    guid_item     = db.Column(db.BINARY(16),db.ForeignKey("items.guid_item"))
    project     = db.relationship(Proyecto, backref=db.backref('list_tags', lazy='dynamic'))
    item        = db.relationship(Item, backref=db.backref('list_tags', lazy='joined'))
    type        = db.Column(db.Integer) #(0,hub);(1,cable);(2,pipe);(3,electrical_pipes)
    created_at  = db.Column(db.DateTime)
    updated_at  = db.Column(db.DateTime)

    def __init__(self,guid_tag,project,item,type,created_at,updated_at):
        # self.guid_item = guid_tag
        self.guid_tag = guid_tag
        self.project = project
        self.item = item
        self.type = type
        self.created_at = created_at
        self.updated_at = updated_at

1 个答案:

答案 0 :(得分:1)

我在docs找到了答案。 考虑Hub是Item的子类。 我必须将backref从连接更改为动态。

class Tag(db.Model):
    __tablename__ = "tags"
    guid_tag      = db.Column(db.BINARY(16), primary_key=True)
    id_project  = db.Column(db.Integer,db.ForeignKey("projects.id_project"))
    guid_item     = db.Column(db.BINARY(16),db.ForeignKey("items.guid_item"))
    project     = db.relationship(Proyecto, backref=db.backref('list_tags', lazy='dynamic'))
    item        = db.relationship(Item, backref=db.backref('list_tags', lazy='joined'))
    type        = db.Column(db.Integer) #(0,hub);(1,cable);(2,pipe);(3,electrical_pipes)
    created_at  = db.Column(db.DateTime)
    updated_at  = db.Column(db.DateTime)

换句话说,我必须避免在同一个会话中有两个持久性对象副本。