Flask-SQLAlchemy:如何根据用户的角色和团队进行查询?

时间:2017-05-11 02:05:28

标签: python flask flask-sqlalchemy flask-admin

我可以将用户列为Role.id == 4的审核者,并且可以由当前用户选择:

def reviewer_choices():
    return User.query.join(User.roles).filter(Role.id == 4)

form_extra_fields = {
     'reviewer1': sqla.fields.QuerySelectField(
      label='Reviewer1',
      query_factory=reviewer1_choices,
)}

现在,如何通过Role.id == 4Team.id == current_user.teams.id查询用户? (限制审核人和当前用户与同一团队

我在下面试过但是徒劳无功:

User.query.join(User.roles).join(User.teams).
     filter(Role.id == 4).filter(Team.id = current_user.teams.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 Team(db.Model, RoleMixin):
     id = db.Column(db.Integer(), primary_key=True)
     name = db.Column(db.String(80), unique=True)
     description = db.Column(db.String(255))

     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'))
     teams = db.relationship('Team', secondary=teams_users,uselist=False,
                        backref=db.backref('users', lazy='dynamic'))
     email = db.Column(db.String(255), unique=True)

     def __str__(self):
         return self.email

class Project(db.Model):

     id = db.Column(db.Integer, primary_key=True)
     reviewer = db.Column(db.Unicode(128))

     def __unicode__(self):
        return self.name

1 个答案:

答案 0 :(得分:1)

更新:

您应该按如下方式定义用户模型:

# -> 1. many to one

class User(db.Model):
    # ...
    team_id = db.Column(db.Integer, db.ForeignKey("team.id"))
    team = db.relationship("Team", foreign_keys=team_id)
    # ...

User.query.filter(Role.id == 4, Team.id == current_user.team_id).all()

# -> 2. one to one

class User(db.Model):
    # ...
    team_id = db.Column(db.Integer, db.ForeignKey("team.id"))
    team = db.relationship("Team", foreign_keys=team_id, uselist=False)
    # ...

User.query.filter(Role.id == 4, Team.id == current_user.team_id).all()

# -> 3. many to many 

users_teams = db.Table(db.Column("user_id", db.Integer(), db.ForeignKey("user.id"),
                       db.Column("role_id", db.Integer(), db.ForeignKey("team.id"))

class User(db.Model):
    # ...
    teams = db.relationship("Team", secondary=users_teams)
    # ...

User.query.filter(Role.id == 4, User.teams.any(Team.id.in_([team.id for team in current_user.teams]))).all()

uselist用于定义一对一的关系。

secondary用于定义多对多的关系。