按关系过滤sqlalchemy Python

时间:2016-12-11 11:10:46

标签: python python-3.x sqlalchemy

有两个表GroupUserusers可以同时属于多个群组。

class Group(db.Model):
       """ Group model """
       __tablename__ = "group"
       id = db.Column(db.Integer, primary_key=True)
       project_id = db.Column(db.Integer, db.ForeignKey("project.id"), nullable=True)
       project = db.relationship("Project", foreign_keys=[project_id])
       active = db.Column(db.Boolean, default=True, index=True)
       name = db.Column(db.String(64), index=True)

用户

class User(db.Model, UserMixin):
    """ User model """
    __tablename__ = "user"

    id = db.Column(db.Integer, primary_key=True)   
    email = db.Column(db.String(128), unique=True, index=True)
    email_confirmed = db.Column(db.Boolean, default=False)    
    password = db.Column(db.String(256), nullable=True)
    groups = db.relationship("Group", secondary=user_has_group, lazy="dynamic",
                     backref=db.backref("users", lazy="dynamic"))

必须为每组用户显示代码

groups = Group.query.all()
for group in groups:
    users = User.query.filter(group in User.groups).all()

但代码未运行。

请帮助我了解每个users的{​​{1}}。

1 个答案:

答案 0 :(得分:1)

您的Userback reference backref=db.backref("users", lazy="dynamic")

因此,从Group对象,您可以使用group.users来获取给定组中的用户,例如

groups = Group.query.all()
for group in groups:
    users = group.users