【问题标题】:Deletion of a row from an association table从关联表中删除一行
【发布时间】:2020-11-23 04:55:38
【问题描述】:

我正在开发一个使用 python3 和 SqlAlchemy 进行 SQLite3 数据库管理的应用程序。我有一些具有多对多关系的表。我创建了一个关联表来处理这种关系。

Class Machine(Base):
    __tablename__ 'machine'
    machine_ID = Column(Integer, primary_key=True)
    etc...
Class Options(Base):
    __tableName__ 'options'
    options_ID = Column(Integer, primary_key=True)
    etc...

The association table

Machine_Options = table('machine_options', Base.metadata,
    Column('machine_FK', Integer, ForeignKey('machine.machine_ID'),
                                 primary_key=True),
    Column('options_FK',Integer, ForeignKey('options.options_ID'),
                                 primary_key=True))

机器和选项的所有项目都是独立插入的。当我想将一台机器与一个选项相关联时,我会使用一个非常有效的附加查询。

我的问题是当我想打破机器和选项之间的这种关联时。我已经尝试使用 machine_FK 和 options_FK 上的 FILTER() 子句从关联表中直接删除行,但 SqlAlchemy 给我一个错误,通知我“Machine_Options”表没有字段“machine_FK”。 我尝试使用机器和选项表的连接间接从“Machine_Options”中删除该行,但收到​​另一个错误,我无法使用连接删除或更新。

我正在寻找只从关联表中删除一行而不影响原始机器或选项表的代码。

到目前为止,我的互联网搜索一直没有结果。

【问题讨论】:

    标签: python-3.x sqlite sqlalchemy relationship


    【解决方案1】:

    我的问题的答案是使用myparent.children.remove(somechild)

    使用machine.children.append(option)进行关联

    使用与“追加”相同的代码并替换为“删除”会取消关联

    代码:

    def removeOption(machineKey,  OptionKey):
    
    session = connectToDatabase()
    
    machineData = session.query(Machine).filter(Machine.machine_ID == machineKey).one()
    optionData = session.query(Options).filter(Options. options_ID == OptionKey).one()
    machineData.children.remove(optionData)
    session.add(machineData)
    session.commit()
    session.close()
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 2012-03-05
      相关资源
      最近更新 更多