Ok, please bear with me as I'm new to SQLAlchemy and Postgres. I have the following models: Lead, Keyword and User.
I have created a many to many relationship between leads and keywords like so:
keyword_identifier = db.Table(
'keyword_identifier',
db.Column('lead_id', db.Integer, db.ForeignKey('leads.id')),
db.Column('keyword_id', db.Integer, db.ForeignKey('keywords.id'))
)
And in my User I have property called keywords, which is an array with keywords id in it.
Now I need to find all leads that are associated with the keywords' id present in the user.keywords list.
I have tried the following:
leads = Lead.query.join(keyword_identifier).join(Keyword).filter(keyword_identifier.c.lead_id.in_([k for k in u.keywords]))
Which brings only 2 results (I know that only one of the keywords have been associated with more than 2000 leads, so definitely not correct).
I have also tried:
for keyword_id in user.keywords:
leads = Lead.query.join(keyword_identifier).join(Keyword).filter(keyword_identifier.c.lead_id == keyword_id)
But that's not bringing the right results either.
Can anyone recommend what would be the best approach here?