SQLAlchemy自动映射-向自动映射的模型添加方法 [英] SQLAlchemy automap - adding methods to automapped Model

查看:58
本文介绍了SQLAlchemy自动映射-向自动映射的模型添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于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兼容,请实现

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆