python - flask 多对多关系导致 "Multiple classes found for path"

标签 python sqlalchemy

我想在 Flask 中定义多对多关系。 (这两个模型是 UserRole。后来我想将它们用于 Flask-Security。)所以我遵循了 http://flask-sqlalchemy.pocoo.org/2.1/models/#many-to-many-relationships并写道

class User(db.Model, UserMixin):
    __tablename__ = 'user'
    __table_args__ = { 'useexisting': True }
    id = Column(Integer, primary_key=True)
    roles = relationship("RolesUsers", backref=db.backref("user", lazy='dynamic'))

class Role(db.Model):
    __tablename__ = 'role'
    __table_args__ = { 'useexisting': True }
    id = Column(Integer, primary_key=True)
    name = Column(String(80), unique=True)


class RolesUsers(db.Model):
    __tablename__ = 'roles_users'
    __table_args__ = { 'useexisting': True }
    user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    role_id= Column(Integer, ForeignKey('role.id'), primary_key=True)

但是我得到了错误

Multiple classes found for path "RolesUsers" in the registry of this declarative base. Please use a fully module-qualified path.

我发现那行

roles = relationship("RolesUsers", backref=db.backref("ma_user", lazy='dynamic'))

似乎对此负责。

你可能会问我为什么用

__table_args__ = { 'useexisting': True }

那是因为否则我得到错误

Table 'user' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

也许这两个错误卡在一起?在我看来,这个类似乎被多次调用了。但我不知道那是怎么来的。那么我该如何修复呢?

最佳答案

我认为关联表的模型类的使用有问题。最后

roles_users = db.Table(
    'ma_roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('ma_user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('ma_role.id'))
)

class User(db.Model, UserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    roles = db.relationship(
        'Role',
        secondary=roles_users,
        backref=db.backref('user', lazy='dynamic')

class Role(db.Model, RoleMixin):
    __tablename__ = "role"
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)

成功了。

关于python - flask 多对多关系导致 "Multiple classes found for path",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46055661/

相关文章:

python - 如何完全关闭sqlalchemy注销

sql - 多表一对一关系

python - plt.show() 可以找到字体,但 plt.savefig() 不能

python - matplotlib 在 IPython 中不使用 matplotlibrc 文件

python,内置打开的默认参数/参数?

python - SQLAlchemy:@property 映射?

python - 测试数据库迁移结果是否与(ORM)一致?楷模

python - 如何在 Flask 中使用 sqlalchemy core 进行分页?

python - 如何在越来越多的任务上使用 asyncio.wait?

python - Google API(gmail 和电子表格): what more should I set up, 或者知道我缺少什么设置?