简体   繁体   English

扩充 Flask-SqlAlchemy 声明性基础

[英]Augmenting Flask-SqlAlchemy declarative base

I tried the following, and it seems to work:我尝试了以下方法,它似乎有效:

class BaseModel(db.Model):
    __abstract__ = True

    row_ver = db.Column(db.Integer, nullable=False)

    @declared_attr
    def __mapper_args__(cls):
        return {'version_id_col': cls.row_ver}

    def to_dict(self):
        res = dict()
        for c in self.__table__.columns:
            value = getattr(self, c.name)
            if isinstance(value, date):
                res[c.name] = value.isoformat()
            elif isinstance(value, uuid.UUID):
                res[c.name] = str(value)
            else:
                res[c.name] = value
        return res

class Account(BaseModel):
    __tablename__ = 'account'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)

I'm not sure whether it is a proper way of augmenting the declarative base class, that is db.Model class.我不确定这是否是扩充声明性基类(即 db.Model 类)的正确方法。 Is there anything wrong with the above code?上面的代码有什么问题吗?

Also related: Is it possible to create custom declarative base by inheriting from db.Model (which itself is declarative base), something like below:还相关:是否可以通过从 db.Model (它本身是声明性基础)继承来创建自定义声明性基础,如下所示:

class Base(db.Model):
    #some code here

from sqlalchemy.ext.declarative import declarative_base 
BaseModel = declarative_base(cls=Base)

class Account(BaseModel)
    #...

To customize db.Model , declare a superclass of flask_sqlalchemy.Model and pass it to model_class as shown below.要自定义db.Model ,请声明一个flask_sqlalchemy.Model的超类并将其传递给model_class ,如下所示。

from flask_sqlalchemy import Model, SQLAlchemy


class AppModel(Model):
    row_ver = db.Column(db.Integer, nullable=False)


db = SQLAlchemy(model_class=AppModel)


class Account(db.Model):
    pass


class Thing(db.Model):
    pass

Note that Account and Thing inherit from db.Model , not AppModel .请注意, AccountThing继承自db.Model ,而不是AppModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM