SqlAlchemy-具有多对多相关模型的左联接查询

时间:2019-03-11 08:27:03

标签: python sql sqlalchemy

我是SqlAlchemy的新手。考虑下表(states_violations)

s_id    v_id
1       1
2       1
2       2
2       3
2       5
2       6
2       7
3       1
3       2
3       6
3       7
3       8
4       1
and so on

这里我想要s_id = 2的记录,而在s_id = 3(v_id 3和5)中不可用

我需要的输出

s_id    v_id
2       3
2       5

通过使用以下查询,我可以获得我的输出
查询1:加入查询:

SELECT a.* FROM states_violations a 
LEFT JOIN states_violations b 
ON a.v_id = b.v_id
   AND b.s_id=3
WHERE a.s_id=2 
   AND b.v_id IS NULL

查询2:嵌套查询:

SELECT states_violations.* FROM states_violations
WHERE s_id = 2
  AND v_id NOT IN (
      SELECT v_id FROM states_violations
      WHERE s_id = 3
      )

Python中的模型类:

# Many-to-many relation between states and violations
states_violations = Table(
    'states_violations', Base.metadata,
    Column('s_id', Integer, ForeignKey('states_table.id')),
    Column('v_id', Integer, ForeignKey('violations_table.id'))
)

class State(Base):
    __tablename__ = "states_table"
    ...
    violations = relationship("Violation", secondary=states_violations,
                              backref="states", lazy='dynamic')

class Violation(Base):
    __tablename__ = "violations_table"
    ...

我想将上述2个查询转换为SqlAlchemy session.query。
由于States_violations是State和Violation模型之间的多对多关系,我们如何将其转换为SqlAlchemy查询?

0 个答案:

没有答案