hello iam trying to get a currnet_user information in my views
and i include from users.models import *
then in my code return return current_user;
<
This depends on what you want to do, are you trying to:
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.
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
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.
Just add extend_existing=True for roles_users as shown below
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')),
extend_existing=True)
I saw this same error using jupyter notebook. I was importing sqlalchemy table classes from a library stored on disk and there was a bug in the definition. After fixing the bug I re-ran the import and saw this error. Simply restarting the jupyter kernel and then rerunning the import resolved the issue.
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