Python SQLAlchemy删除多对多行

Python SQLAlchemy删除多对多行,python,postgresql,sqlalchemy,Python,Postgresql,Sqlalchemy,我正在使用一个带有sqlalchemy(新的)和python的postgresql数据库 我想删除bot和钱包/鲸鱼之间的关系。 如果可能的话,如果关系表中没有其他bot,也可以删除鲸鱼 以下是模型: WhaleBot = Table('whale_bot', Base.metadata, Column('id', Integer, primary_key=True, nullable=False), Column('whale_id', Integer, ForeignKey(

我正在使用一个带有sqlalchemy(新的)和python的postgresql数据库

我想删除bot和钱包/鲸鱼之间的关系。 如果可能的话,如果关系表中没有其他bot,也可以删除鲸鱼

以下是模型:

WhaleBot = Table('whale_bot', Base.metadata,
    Column('id', Integer, primary_key=True, nullable=False),
    Column('whale_id', Integer, ForeignKey('whales.id'), nullable=False),
    Column('bot_id', Integer, ForeignKey('bots.id'), nullable=False),
    Column('created_at', DateTime(timezone=True), server_default=func.now(), nullable=False),
    Column('updated_at', DateTime(timezone=True), default=func.now(), onupdate=func.now(), nullable=False),
    UniqueConstraint('whale_id', 'bot_id', name='uix_1')

class Whale(Base):
    __tablename__ = 'whales'

    id = Column(Integer, primary_key=True, nullable=False)
    wallet = Column(String, unique=True, nullable=False)
    is_contract = Column(Boolean, nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), default=func.now(), onupdate=func.now(), nullable=False)

    bots = relationship('Bot', secondary=WhaleBot, cascade="all, delete", backref='Whale')

class Bot(Base):
    __tablename__ = 'bots'

    id = Column(Integer, primary_key=True, nullable=False)
    name = Column(String, nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), default=func.now(), onupdate=func.now(), nullable=False)

    whales = relationship('Whale', secondary=WhaleBot, cascade="all, delete", backref='Bot')
)


下面是我目前尝试的代码:

def delete_wallet(self, wallet, botId):
        try:
            walletId = self.dbEngine.session.query(Whale.id).filter(Whale.wallet == wallet).scalar()
            toDelete =self.dbEngine.session.query(WhaleBot).filter(WhaleBot.c.bot_id == botId).filter(WhaleBot.c.whale_id == walletId).first()
            print(toDelete.id)
            #WhaleBot.query().filter(id == toDelete.id).delete()
            #self.dbEngine.session.query(WhaleBot).query.filter(id == toDelete.id).delete()
            #self.dbEngine.session.query(WhaleBot).filter_by(id == toDelete.id).delete()
            # toDelete = self.dbEngine.session.query(Whale).filter(Whale.wallet == wallet).scalar()
            #self.dbEngine.session.delete(WhaleBot).filter(WhaleBot.c.id == toDelete)
            obj = self.dbEngine.WhaleBot.filter_by(id == toDelete.id).one()
            #obj = User.query.filter_by(id=123).one()
            self.dbEngine.session.delete(obj)

            self.dbEngine.session.commit()
            return True, "Deleted"
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            with open("errorlog.txt",'a') as f:
                f.write("delete error: "+dt.now().strftime('%Y-%m-%d %H:%M:%S')+" "+str(e)+ "\n"+
                str(fname)+" Line: "+str(exc_tb.tb_lineno)+ "\n")
            return False, "Something wrong"


我让评论进来,这样你就可以看到我试了很多

这里是一些我遇到的错误案例。。。也许你可以告诉我哪里错了,这样我就可以理解sqlalchemy——但也可以找到一个解决方案:) 案例1

错误案例1:

'DBEngine' object has no attribute 'WhaleBot'
案例2(可在互联网上找到):

错误案例2:

'Query' object has no attribute 'query'
案例3:

walletId = self.dbEngine.session.query(Whale.id).filter(Whale.wallet == wallet).scalar()
toDelete =self.dbEngine.session.query(WhaleBot).filter(WhaleBot.c.bot_id ==botId).filter(WhaleBot.c.whale_id == walletId).first()
self.dbEngine.session.query(WhaleBot).filter_by(WhaleBot.c.id == toDelete.id).delete()
错误案例3:

'NoneType' object has no attribute 'class_'
这一点也像我说的,我是SQLalchemy新手,不知道在哪里搜索(我的代码/偏差或我调用函数的方式…)


是的,还有很多其他我尝试过的方法。。。但是有足够的例外xD

您可以像这样删除关系:

whale = session.query(Whale).filter(Whale.wallet == wallet).one()
bot = session.query(Bot).get(botId)
whale.bots.remove(bot)
session.commit()
或者反过来说:

whale = session.query(Whale).filter(Whale.wallet == wallet).one()
bot = session.query(Bot).get(botId)
whale.bots.remove(bot)
session.commit()

请参阅有关删除多个至五月关系的文档。

Ahh尝试过。。。我明白我的理解问题。。。试图直接在关系表中删除,但需要在关系表中删除^^谢谢
whale = session.query(Whale).filter(Whale.wallet == wallet).one()
bot = session.query(Bot).get(botId)
whale.bots.remove(bot)
session.commit()
whale = session.query(Whale).filter(Whale.wallet == wallet).one()
bot = session.query(Bot).get(botId)
whale.bots.remove(bot)
session.commit()