python - Table 'roles_users' is already defined for this MetaData instance

ID : 131341

viewed : 10

Tags : pythonsqlalchemypython

Top 5 Answer for python - Table 'roles_users' is already defined for this MetaData instance

vote vote

94

Try adding:

__table_args__ = {'extend_existing': True}

right below __tablename__

Reference: https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html?highlight=table_args

vote vote

85

I had a similar error. My problem was importing the class that inherits db.Model from two different files using a relative import. Flask-SQLAlchemy mapped the two imports as two different table definitions and tried to create two tables. I fixed this issue by using the absolute import path in both files.

vote vote

74

I had this error when I had created a new class by copy-pasting a previous class. It turned out I had forgotten to change the __tablename__, so I had two classes with the same __tablename__ property. This caused the error, and changing the property resolved it.

vote vote

69

This depends on what you want to do, are you trying to:

  1. delete the old class and repalce it with a new class mapping? Or,
  2. Keep the old class and just restart your app?

In the first case using your example above, try running the following line before defining your classes:

db.metadata.clear() 

The reason is the first time you declare a SQLAlchemy Mapping by defining a python class, the definition of the class is saved to the metadata object, in order to prevent conflicts caused by multiple definitions being mapped to the same table.

When you call the clear() method you clear all the table definitions held in memory by the Metadata object, which allows you to declare them again.

In the second case when you're just restarting the app I would write a test to see if the table already exists using the reflect method:

db.metadata.reflect(engine=engine) 

Where engine is your db connection created using create_engine(), and see if your tables already exist and only define the class if the table is undefined.

vote vote

58

Its one year late but if someone doesn't find the solution in the given answers may be this can solve the problem -

I had this same problem with my class which was inherited from db.Model (of flask_sqlalchemy).

My code looked like this -

class MasterDB(db.Model):     __tablename__ = 'masterdb'     __table_args__ = {'schema': 'schema_any'}     ...     ... 

Resolved it by specifying the abstract property to True in the class variable list. Add it in the class variable list like this and it should work -

class MasterDB(db.Model):     __tablename__ = 'masterdb'     __table_args__ = {'schema': 'schema_any'}     __abstract__ = True 

Top 3 video Explaining python - Table 'roles_users' is already defined for this MetaData instance

Related QUESTION?