Psychadia
Psychadia

Reputation: 1

How to join with SQLAlchemy from a ref attribute

Title is very confused, my bad about that, but i will explain my problem.

I have 3 tables:

extract code of Entity1

class Entity1(db.Model):
    ...

    entity2 = db.relationship('Entity2', lazy='joined')

extract code of Entity2

class Entity2(db.Model):
    ...

    entity3 = db.relationship('Entity3', lazy='joined')

And I want to make a join from Entity1.entity2 toward Entity3 table and add an WHERE clause on entity3 attribute.

I tried this:

query = Entity1.query    
query = query.join(Entity1.entity2.entity3).filter(entity2.entity3.has(code=input))

and multiple variants...

Upvotes: 0

Views: 35

Answers (1)

van
van

Reputation: 76992

Below should work (either version-1 or version-2 filters):

query = (
    Entity1.query
    .join(Entity2, Entity1.entity2)
    .filter(Entity2.entity3.has(Entity3.code == input))  # version-1
    # .join(Entity3, Entity2.entity3).filter(Entity3.code == input)  # version-2
)

Upvotes: 0

Related Questions