SQLAlchemy更新/删除关联表以及其他列

时间:2019-03-10 21:05:32

标签: many-to-many associations flask-sqlalchemy

我对SQLAlchemcy非常陌生。有人可以帮助我了解如何更新额外数据或删除关联表中的整行。

下面的代码直接来自SQLAlchemy文档。

class Association(Base):
     __tablename__ = 'association'
     left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
     right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
     extra_data = Column(String(50))
     child = relationship("Child", back_populates="parents")
     parent = relationship("Parent", back_populates="children")

class Parent(Base):
     __tablename__ = 'left'
     id = Column(Integer, primary_key=True)
     children = relationship("Association", back_populates="parent")

class Child(Base):
     __tablename__ = 'right'
     id = Column(Integer, primary_key=True)
     parents = relationship("Association", back_populates="child")


# create parent, append a child via association
p = Parent()
a = Association(extra_data="some data")
a.child = Child()
p.children.append(a)

# iterate through child objects via association, including association
# attributes

    for assoc in p.children:
        print(assoc.extra_data)
        print(assoc.child)

现在,我知道如何使用上述代码将数据添加到“关联”表中,但是有些可以帮助我了解如何删除/更新该行。我尝试了以下代码,但出现错误。

p.children.remove(a)
#error is
Dependency rule tried to blank-out primary key column 'association.left_id'

谢谢。

0 个答案:

没有答案