SQLAlchemy automap - adding methods to automapped Model

这一生的挚爱 提交于 2021-01-29 01:59:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!