SQLAlchemy自动映射-向自动映射的模型添加方法 [英] SQLAlchemy automap - adding methods to automapped Model
问题描述
我有一个用于SQLAlchemy的预先存在的数据库,因此我正在使用自动映射从数据库中获取模型.向这些类添加方法的最佳方法是什么?例如,对于User类,我想添加诸如验证密码之类的方法.另外,我想为flask-login(UserMixin)方法添加方法.
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.
推荐答案
事先明确指定您的类,然后像通常那样定义方法:
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)
现在 Base.classes.User
和 User
相同,并带有其他方法.要使您的 User
类flask-login兼容,请实现 UserMixin
到您的 User
类.mixin似乎只希望您的 User
类中存在一个 id
属性/列.
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.
这篇关于SQLAlchemy自动映射-向自动映射的模型添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!