使用SQLAlchemy查询具有关联对象的元素

时间:2016-10-31 15:27:40

标签: python sqlalchemy

我是SQLAlchemy的新手。我有这个型号:

class AssociationUserClub(db.Model):
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    club_id = db.Column(db.Integer, db.ForeignKey('club.id'), primary_key=True)
    roleClub = db.Column( db.String(50) , nullable = False, server_default = "member" )
    club = db.relationship("Club", back_populates="members")
    user = db.relationship("User", back_populates="clubs")

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(200), unique=True)
    clubs = db.relationship("AssociationUserClub", back_populates="user")

class Club(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column( db.String(255), unique = True, nullable = False )
    members = db.relationship("AssociationUserClub", back_populates="club")

我想要一个用户在他所属的所有俱乐部中知道的所有用户的列表。

我尝试这个,但我找不到正确的答案:

User.query.filter( User.clubs.any( xxxx) ).all()

非常感谢

1 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题就会有这样的工作吗?

#get all users
users = User.query.all()

# for each user, look at the list of clubs they are in, and generate the list of the club
for user in users:
    clubs = user.clubs
    for club in clubs:
        # friends are = members of the club, if that member is not the user
        # Ill use List comprehension for that.
        friends = [member for member in club.members if member.user_id != user.id]



        # edit, if you want to remember the club they are associated with
        friends = dict([(member.club_id, member) for member in club.members if member.user_id != user.id])