Flask SQLAlchemy从蓝图基础模型扩展关系模型

时间:2017-09-09 16:05:10

标签: python flask sqlalchemy flask-sqlalchemy

我在博客蓝图上的主要models.py和Post模型上有一个User模型。我想创建一个包含ForeignKey的基础BlogUser,我可以在主应用程序上扩展User模型,以创建User和Post模型之间的一对多关系。以下是代码。

应用程序/ models.py

from app import db
from flask_login import UserMixin
from flask_bcrypt import generate_password_hash
from app.blueprints.blog.models import BlogUser

class User(BlogUser, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), unique=True, nullable=False)
    email = db.Column(db.String(250), unique=True, nullable=False)
    password = db.Column(db.String(32), nullable=False)
    is_admin = db.Column(db.Boolean, default=False)

    def __init__(self, username, email, password, is_admin):
        self.username = username
        self.email = email
        self.password = generate_password_hash(password)
        self.is_admin = is_admin

    def __repr__(self):
        return '<User %r>' % self.username

应用程序/蓝图/博客/ models.py

from app import db
from datetime import datetime

class BlogUser(db.Model):
    __abstract__ = True
    posts = db.relationship('Post', backref='author', lazy='dynamic')

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), nullable=False)
    body = db.Column(db.Text, default='')
    pub_date = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __init__(self, title, body, author, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.author = author

    def __repr__(self):
        return '<Post %r>' % self.title

这是我得到的错误:

Traceback (most recent call last):
  File "C:/Users/vsantiago/Desktop/flask app template/application.py", line 1, in <module>
    from app import app as application
  File "C:\Users\vsantiago\Desktop\flask app template\app\__init__.py", line 18, in <module>
    from app import views
  File "C:\Users\vsantiago\Desktop\flask app template\app\views.py", line 6, in <module>
    from app.models import User
  File "C:\Users\vsantiago\Desktop\flask app template\app\models.py", line 6, in <module>
    class User(BlogUser, UserMixin):
  File "C:\pyenv\featurerequest\lib\site-packages\flask_sqlalchemy\__init__.py", line 602, in __init__
    DeclarativeMeta.__init__(self, name, bases, d)
  File "C:\pyenv\featurerequest\lib\site-packages\sqlalchemy\ext\declarative\api.py", line 64, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "C:\pyenv\featurerequest\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 88, in _as_declarative
    _MapperConfig.setup_mapping(cls, classname, dict_)
  File "C:\pyenv\featurerequest\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 103, in setup_mapping
    cfg_cls(cls_, classname, dict_)
  File "C:\pyenv\featurerequest\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 123, in __init__
    self._scan_attributes()
  File "C:\pyenv\featurerequest\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 216, in _scan_attributes
    "Mapper properties (i.e. deferred,"
sqlalchemy.exc.InvalidRequestError: Mapper properties (i.e. deferred,column_property(), relationship(), etc.) must be declared as @declared_attr callables on declarative mixin classes.

1 个答案:

答案 0 :(得分:0)

就像错误状态将直接relationship属性移动到BlogUser抽象基类中的@declared_attr装饰可调用对象一样:

from sqlalchemy.ext.declarative import declared_attr


class BlogUser(db.Model):
    __abstract__ = True

    @declared_attr
    def posts(cls):
        return db.relationship('Post', backref='author', lazy='dynamic')