简体   繁体   中英

How do I add join conditions on many to many relationships in SQL Alchemy?

I have the models A and B , connected in a many-to-many relationship using the secondary parameter referring to the model AB (the association table).

Using query(A).options(joinedload(Ab)) will generate the query:

SELECT ...
FROM a
LEFT OUTER JOIN (a_b AS a_b_1 JOIN b ON b.id = a_b_1.b_id) ON a.id = a_b_1.a_id

But I want extra conditions on the join (not using WHERE!), in order to filter on a certain flag in B . So just like this:

SELECT ...
FROM a
LEFT OUTER JOIN (a_b AS a_b_1 JOIN b ON b.id = a_b_1.b_id AND b.flag = 1) ON a.id = a_b_1.a_id

How do I do that using SQL Alchemy?

You can use and_() expression with .outerjoin() . Just an example with 2 models:

from sqlalchemy import and_

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)


class B(Base):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer)
    flag = Column(String)


a = A()
session.add(a)
session.commit()

# just a few records. without flag + with flag
b1 = B(a_id=a.id)
b2 = B(a_id=a.id, flag='Cs_Is_Better')

session.add(b1)
session.add(b2)
session.commit()

query = session.query(A).outerjoin(B, (and_(A.id == B.a_id, B.flag == 'Cs_Is_Better')))

print(query)
# SELECT a.id AS a_id 
# FROM a LEFT OUTER JOIN b ON a.id = b.a_id AND b.flag = %(flag_1)s
print(query.all())  # [<__main__.A object at 0x112fb4780>]

So just add any conditions to outerjoin :

.outerjoin(ModelName, (and_(...))

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM