sqlalchemy有几个到多个表连接

时间:2011-01-13 12:11:13

标签: python sqlalchemy join

SQLalchemy的新功能,这是我的问题:

我的模特是:

user_group_association_table = Table('user_group_association', Base.metadata,
    Column('user_id', Integer, ForeignKey('user.id')), 
    Column('group_id', Integer, ForeignKey('group.id'))    
)

department_group_association_table = Table('department_group_association', Base.metadata,
    Column('department', Integer, ForeignKey('department.id')), 
    Column('group_id', Integer, ForeignKey('group.id'))
)

class Department(Base):
    __tablename__ = 'department'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))


class Group(Base):
    __tablename__ = 'group'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    users = relationship("User", secondary=user_group_association_table, backref="groups")
    departments = relationship("Department", secondary=department_group_association_table, backref="groups")

class User(Base):

    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    firstname = Column(String(50))
    surname = Column(String(50))

因此,此代码反映了以下关系:

   --------             ---------             --------------
   | User | --- N:M --- | Group | --- N:M --- | Department |
   --------             ---------             --------------

我尝试使用连接但仍未成功执行以下操作:

一个sqlalchemy请求获取所有用户实例,同时知道一个部门名称(让我们说'R& D')

这应该从:

开始
session.query(User).join(...
or
session.query(User).options(joinedLoad(...

任何人都可以提供帮助吗?

感谢您的时间,

皮尔

2 个答案:

答案 0 :(得分:22)

session.query(User).join((Group, User.groups)) \
    .join((Department, Group.departments)).filter(Department.name == 'R&D')

这也有效,但使用了一个子选择:

session.query(User).join((Group, User.groups)) \
    .filter(Group.departments.any(Department.name == 'R&D'))

答案 1 :(得分:1)

为什么不创建table relationships

实施后,获得您想要的:

list_of_rnd_users = [u for u in Users if 'R&D' in u.departments]

其中.departments属性是您关系的属性。