In sqlalchemy I defined a model for my database, in this case two tables "sample" and "experiment", which are linked over a many-to-many relationship to each other:
class Sample(Base):
__tablename__ = 'sample'
id = Column(Integer, primary_key=True)
name = Column(String)
date = Column(String)
class Experiment(Base):
__tablename__ = 'experiment'
id = Column(Integer, primary_key=True)
name = Column(String)
description = Column(String)
result = Column(String)
samples = relationship('Sample', secondary='sample_has_experiment', backref="experiments")
t_sample_has_experiment = Table(
'sample_has_experiment', metadata,
Column('sample_id', ForeignKey('sample.id'), primary_key=True, nullable=False, index=True),
Column('experiment_id', ForeignKey('experiment.id'), primary_key=True, nullable=False, index=True)
)
In my database, I have a sample "Dilithium", and in experiments two experiments "Cold fusion" and "Worm hole".
I try to query the "Worm hole" experiment over a join to the sample table:
samples = s.query(Obj.Sample).join(Obj.Sample.experiments).\
filter(Obj.Experiment.name == "Worm hole").all()
for sample in samples:
for experiment in sample.experiments:
print(experiment.name)
But as a result I still get both experiments "Worm hole" AND "Cold Fusion". So it looks like the filtering is not applied. How can I filter that way that I only receive the "Worm Hole" Experiment object? Thank you.
@Dublicate: Indeed it looks like the same question, but the given answer does not solve my problem. In my opinion, my suggested query does exactly the same like in the proposed answer.