我创建了与多对多关系相关联的User
和Group
个模型。在下一阶段,我试图弄清楚如何将Permission
模型连接到这两个模型。用户和组将共享相同的权限表。我正在查看SQLAlchemy文档中有关polymorphically连接表的示例,我找不到适合我案例的任何示例。也许我错了。如果有人指出我正确的方向,展示解决方案或分享他的实施,我会很高兴。
我目前的代码已简化:
from app import db
groups = db.Table('groups',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('group_id', db.Integer, db.ForeignKey('group.id')),
)
class Permission(db.Model):
__tablename__ = 'permission'
id = db.Column(db.Integer, primary_key=True)
content_type = db.Column(db.String(50))
codename = db.Column(db.String(100))
#__mapper_args__ = { # are those set right?
# 'polymorphic_identity': 'permission',
# 'polymorphic_on': content_type
#}
class Group(db.Model):
__tablename__ = 'group'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(80), unique=True)
#__mapper_args__ = { # Is this set right?
# 'polymorphic_identity': 'group',
#}
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Unicode(50), unique=True)
groups = db.relationship('Group',
secondary=groups,
backref=db.backref('users', lazy='dynamic'),
lazy='dynamic')
# ... and other nonrelevant fields ...
#__mapper_args__ = { # Is this set right?
# 'polymorphic_identity': 'user',
#}
编辑:提出更清楚的问题。