Python SQL-Alchemy很多关系

时间:2018-06-07 22:44:22

标签: python flask-sqlalchemy

我想像这样做关系: enter image description here

所以我的模型以这种方式定义:

role_user = db.Table('role_user',
        db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer, db.ForeignKey('role.id')))

permission_role = db.Table('permission_role',
        db.Column('permission_id', db.Integer, db.ForeignKey('permission.id')),
        db.Column('role_id', db.Integer, db.ForeignKey('role.id')))


class role(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255))
    display_name = db.Column(db.String(255))
    description = db.Column(db.String(255))



class permission(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255))
    display_name = db.Column(db.String(255))
    description = db.Column(db.String(255))
    costam2 = db.relationship('role', secondary=permission_role, backref=db.backref('permissions', lazy='dynamic'))


class user(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255))
    email = db.Column(db.String(255))
    password = db.Column(db.String(255))
    costam1 = db.relationship('role', secondary=role_user, backref=db.backref('users', lazy='dynamic'))

我正在向db添加记录,如下所示:

admin = permission(name='admin', display_name='Admin', description='Admin')
operator = permission(name='operator', display_name='Operator', description='Operator')
ordinary_user = permission(name='ordinary_user', display_name='Ordinary user', description='Ordinary user')
db.session.add_all([admin, operator, ordinary_user])

user1 = user(name='user1', email='user1@user.pl', password='user1pass')
user2 = user(name='user2', email='user2@user.pl', password='user2pass')
user3 = user(name='user3', email='user3@user.pl', password='user3pass')
user4 = user(name='user4', email='user4@user.pl', password='user4pass')
db.session.add_all([user1, user2, user3, user4])

role1 = role(name='role1', display_name='role1', description='role1')
role2 = role(name='role2', display_name='role2', description='role2')
role3 = role(name='role3', display_name='role3', description='role3')
role4 = role(name='role4', display_name='role4', description='role4')
db.session.add_all([role1, role2, role3, role4])

到目前为止一切都还好。当我试图将它们联系起来时,问题就出现了,例如:

user1.permissions.append(admin)

结果是:AttributeError: 'user' object has no attribute 'permissions'

在定义这些模型时,我是否犯了错误?也许backref错了?

1 个答案:

答案 0 :(得分:1)

permission课程中,您通过permissionsbackref课程创建role属性,而不是user课程。

costam2 = db.relationship('role', secondary=permission_role, backref=db.backref('permissions', lazy='dynamic'))

应该是

costam2 = db.relationship('user', secondary=permission_role, backref=db.backref('permissions', lazy='dynamic'))

这至少可以解决该特定错误

仔细查看图表。也许你想做类似的事情:

role1.permissions.append(admin)

然后在roleuser

之间创建关系