2011-01-13 78 views
8

新與SQLAlchemy的,這裏是我的問題:幾個多對多表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的請求,讓所有的用戶實例,同時瞭解一個DEPARTEMENT名(假設「R & d「)

這應該啓動:

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

任何人都可以幫助嗎?

感謝您的時間,

皮埃爾

回答

1

你爲什麼不創建一個table relationships

實現它之後,獲得您想要的:

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

其中.departments屬性將是你的關係的性質。

21
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'))