问题
I have a preexisting database that I'm using with SQLAlchemy, so I'm using automap to get the Models from the database. What is the best way to add methods to these classes? For example, for a User class, I'd like to add methods such as verifying the password. Also, I'd like to add methods for flask-login (UserMixin) methods.
回答1:
Specify your classes explicitly beforehand, and define your methods as you would normally:
Base = automap_base()
class User(Base):
__tablename__ = 'user'
def verify_password(self, password):
...
Base.prepare(engine, reflect=True)
Now Base.classes.User
and User
are the same, with your additional methods. To make your User
class flask-login compatible, implement the listed attributes and methods, or add the provided UserMixin to your User
class. The mixin seems to only expect the existence of an id
attribute/column from your User
class.
来源:https://stackoverflow.com/questions/39417143/sqlalchemy-automap-adding-methods-to-automapped-model