hatooku hatooku - 1 year ago 203
Python Question

SQLAlchemy automap - adding methods to automapped Model

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.

Answer Source

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.