python - Flask-sqlalchemy:如何制作一个可选择按钮来根据用户的角色 ID 选择用户?

标签 python flask-sqlalchemy flask-admin

这是基于 flask-admin example .

我想构建一个可选择的下拉按钮来根据角色 ID 选择数据库中的用户而不是所有用户。

例如:说 super 用户(role id=2),我如何制作一个可选按钮,仅限制可以选择 super 用户的用户(在我的类项目)?

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


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

     def __str__(self):
        return self.name

class User(db.Model, UserMixin):
     id = db.Column(db.Integer, primary_key=True)
     roles = db.relationship('Role', secondary=roles_users,
                         backref=db.backref('users', lazy='dynamic'))
     email = db.Column(db.String(255), unique=True)

     def __str__(self):
         return self.email

class Project(db.Model):
      *some code here make the selectable button to select users that are superusers*

角色表:

enter image description here

角色-用户表:

enter image description here

enter image description here

最佳答案

您的User模型定义了与Role模型的多对多关系。您可以使用此关系通过角色 ID 查询用户。

users = User.query.join(User.roles).filter(Role.id == 123).all()

或者,您可以先查询Role,然后使用users 属性访问该角色的用户。

role = Role.query.get(123)
users = role.users

有关详细信息,请参阅 SQLAlchemy 文档:

关于python - Flask-sqlalchemy:如何制作一个可选择按钮来根据用户的角色 ID 选择用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43488215/

相关文章:

python - 发电机不能自己耗尽

python-3.x - Flask sqlalchemy 将列表保存为 json

python - (Python3) flask 管理员: It is possible to full utilise the table to view data

python - 在一个范围内生成多组随机的、不重叠的间隔

python - Keras 源代码 : how to reach?

casting - Sqlalchemy 查询返回 Decimal 对象

Flask-Admin ModelView 没有正确处理外键(空白下拉菜单)

python - Flask-Admin 中字段的自定义名称

Python - 输入用户输入的天数,然后显示等效的年、月和日

python - 如何在 Flask SQLAlchemy 中按多个条件进行过滤?