This error occurs when you try to attach an instance to a session in SQLAlchemy, but another instance with the same key is already present in the session.\n\nIn your case, it seems like you are trying to attach an instance of the HandleDuidian class to a session. However, there is already another instance of HandleDuidian with the key (188464,) present in the session.\n\nTo resolve this issue, you can either remove the existing instance from the session before attaching the new one, or update the existing instance instead of attaching a new one. Here's an example of how you can remove the existing instance from the session:\n\npython\nfrom sqlalchemy.orm import sessionmaker\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nexisting_instance = session.query(HandleDuidian).get((188464,))\nsession.delete(existing_instance)\n\nnew_instance = HandleDuidian(...)\nsession.add(new_instance)\n\nsession.commit()\n\n\nIn this example, we first query the existing instance with the key (188464,) from the session using session.query(HandleDuidian).get((188464,)). We then use session.delete() to remove the existing instance from the session.\n\nAfter that, you can attach the new instance to the session using session.add() and commit the changes with session.commit().

SQLAlchemy InvalidRequestError: Can't Attach Instance - Duplicate Key Solution

原文地址: https://www.cveoy.top/t/topic/pV5v 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录