class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
default = db.Column(db.Boolean, default=False, index=True)
permissions = db.Column(db.Integer)
users = db.relationship('User', backref='role', lazy='dynamic')
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.Integer, unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
password_hash = db.Column(db.String(128))
confirmed = db.Column(db.Boolean, default=False)
def can(self, permissions):
print(self.role) #None
return self.role is not None and (self.role.permissions & permissions) == permissions
@main.route('/',methods=['GET', 'POST'])
def index():
form = PostForm()
print(current_user.role) #None
print(current_user.can(Permission.WRITE_ARTICLES)) #False
if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
post = Post(body=form.body.data, author=current_user._get_current_object())
db.session.add(post)
return redirect(url_for('.index'))
posts = Post.query.order_by(Post.timestamp.desc()).all()
return render_template('index.html', form=form, posts=posts)
sqlite> .tables
alembic_version posts roles users
sqlite> select * from roles;
1|Administrator|0|255
2|Moderator|0|15
3|User|1|7
角色中有数据,但print(current_user.role)为None,当我在类User中调用can函数时,print(self.role)也是None。
我无法理解为什么self.role是None?