delhi09の勉強日記

技術トピック専用のブログです。自分用のメモ書きの投稿が多いです。あくまで「勉強日記」なので記事の内容は鵜呑みにしないでください。

「sqlalchemy.exc.InvalidRequestError: Table 'table_name' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.」が発生

概要

SQLAlchemyでMySQLにデータをInsertしようとしたところ、以下のエラーが発生した。
エラーの原因は調査できていないが、とりあえず解消方法は見つかったので備忘録としてメモしておく。

sqlalchemy.exc.InvalidRequestError: Table 'table_name' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

環境

  • Python 3.7.3
  • SQLAlchemy 1.3.17
  • MySQL5.7.30

解消方法

Tableインスタンスを作成する時のコンストラクタの引数にextend_existing=Trueを付ける。

(例)

user = Table(
            "user",
            metadata,
            Column("user_id", Integer, nullable=False, primary_key=True),
            Column("user_name", String(64), nullable=False),
            Column("password", String(64), nullable=False),
            extend_existing=True
        )

参考文献

・公式ドキュメント
docs.sqlalchemy.org

・stack overflow
stackoverflow.com