Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

flask--数据库 如何改变一个用户的角色?

学习Flask-SQLAlchemy,求教如何更改用户的角色。
如果现在创建了角色 Administrator、User、Moderator,id依次为1、2、3。 用户 L, id为1,L的角色为User。 请问怎样在python shell中更改用户的角色???


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

假设模型是这样的:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(), unique=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    

根据你说的,假设有用户L(id=1, username='xxx', role_id=2)

>>> u=User.query.get_or_404(1)#忽略import语句
>>> u.role_id=1
>>> db.session.add(u)
>>> db.session.commit()
>>> u.role_id
1

则此时用户角色变为了Administrator。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...