小编典典

如何查询包含user_x的所有'foo'类型的组?(多对多表格)

sql

鉴于下表下面,我该如何查询grouptype的所有群体'foo'user_x

等效的SQL将类似于:

SELECT * FROM users_to_groups
    LEFT JOIN users ON user_id=users.id
    LEFT JOIN groups ON group_id=groups.id
    WHERE groups.type='type1' AND user_id=1;

我以为SQLAlchemy查询看起来像这样:

session.query(UserGroup).filter(UserGroup.user==user_x,
                                UserGroup.group.grouptype=='foo')

但我不知道如何指定grouptype(上面的查询引发此异常:AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with UserGroup.group has an attribute 'grouptype'

users_to_groups = Table(
    'users_to_groups', Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
    Column('group_id', Integer, ForeignKey('groups.id'), primary_key=True),
)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    groups = relationship('Group',
                          secondary=users_to_groups,
                          backref=backref('users',
                                          collection_class=set),
                          collection_class=set)

class Group(Base):
    __tablename__ = 'groups'
    id = Column(Integer, primary_key=True)
    grouptype = Column(String)

Base.metadata.create_all(engine)

class UserGroup(object):
    pass

mapper(UserGroup, users_to_groups,
        properties={
            'group' : relationship(Group),
            'user' : relationship(User),
})

我将sqlalchemy 0.8.2与Postgres 9.2.4一起使用。


阅读 168

收藏
2021-04-22

共1个答案

小编典典

您可以使用RelationshipProperty.Comparator.has()

session.query(UserGroup).filter(UserGroup.user == user_x,
                                UserGroup.group.has(Group.grouptype == 'foo'))

您可能会发现Group直接查询更自然:

session.query(Group).filter(Group.users.any(User.id == user_x), 
                            Group.grouptype == 'foo')
2021-04-22