带有SQLAlchemy的多人关系w / Mixins

时间:2015-12-24 01:36:46

标签: python sqlalchemy flask-sqlalchemy

我遇到的问题如下:在以下代码块中,您可以看到我想要分隔idcreated_onupdated_on属性,以便我跟随Don不要重复自己(DRY)原则。

# Used to generalize a default database model with an ID
class IdentifierMixin(object):
    id = db.Column(db.Integer, primary_key=True)


# Used to generalize timestamps on the default database model
class TimestampMixin(object):
    created_on = db.Column(db.DateTime, server_default=db.func.now())
    updated_on = db.Column(db.DateTime, server_default=db.func.now(),
                           onupdate=db.func.now())


# The many-to-many relationships
users_roles = db.Table('users_roles',
                db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
                db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))


class User(declarative_base(), IdentifierMixin, TimestampMixin, UserMixin):
    __tablename__ = 'user'

    # Relationships
    roles = db.relationship('Role', secondary=users_roles,
                        backref=db.backref('users', lazy='dynamic'))
    uploads = db.relationship('Upload', backref='uploader', lazy='dynamic')

    email = db.Column(db.String(100), nullable=False, unique=True)
    username = db.Column(db.String(40), nullable=True, unique=True)
    password = db.Column(db.String, nullable=False)
    authenticated = db.Column(db.Boolean, default=False)

    # True, as all users are active
    def is_active(self):
        return True

    # Return the email address to satisfy Flask-Login's requirements
    def get_id(self):
        return self.email

    # Return the authenticated parameter
    def is_authenticated(self):
        return self.authenticated

    # False, anonymous users are not supported
    def is_anonymous(self):
        return False

    def __repr__(self):
        if self.username is not None:
            return '<User %r>' % self.username
        else:
            return '<User %r>' % self.email


class Role(declarative_base(), IdentifierMixin, RoleMixin):
    __tablename__ = 'role'

    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

但是,似乎无法找到id属性(继承自IdentifierMixin mixin):

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'users_roles.user_id' could not find table 'user' with which to generate a foreign key to target column 'id'

有人可以解释一下我做错了什么吗?我非常喜欢它。关于蒂姆。

0 个答案:

没有答案