The table was already created using sqlalchemy.
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
mobile = db.Column(db.String(20))
email = db.Column(db.String(50))
notification = db.Column(db.String(5))
admin = db.Column(db.Boolean, default=False)
superuser = db.Column(db.Boolean, default=False)
def __str__(self):
return self.name
def __repr__(self):
return "<User(name='%s', admin='%s')>" % (
self.name,
self.admin
)
Then I added a column through the command line mysql utility, now I want to access it through python. Is there a way to add it to the model ?
CodePudding user response:
If you do not have a single location where your models's schema are defined (python SQLAlchemy SQL script executed manually), then you'll need to reflect the tables/models from the database (which does have the full schema).
Reflecting can be done in several of ways, I'll put here the simplest method (autoloaded __table__
) inspired by the documentation (see my other answer for other examples).
from sqlalchemy import Table, create_engine
from sqlalchemy.orm import declarative_base
Base = declarative_base() # same declarative_base() as usual
engine = create_engine("sqlite:///mydatabase.db") # get your engine
class User(Base):
__table__ = Table("user", Base.metadata, autoload_with=engine)