模型是这样的(在SQLAlchemy中):
Class Cell(Base):
__tablename__ = "cell"
id = Column(Integer)
name = Column(String)
Class Sample(Base):
__tablename__ = "cell"
id = Column(Integer)
factor_id = Column(Integer, ForeignKey("cell.id"))
cell = relationship(Cell, backref = 'sample', order_by = "Cell.id")
当我执行这样的查询时:
DBSession.query(Sample).filter(Sample.cell.name == "a_string")
它会抛出这样的异常:
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/attributes.py", line 139, in __getattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'name'
cell
类中的Sample
字段似乎没有名为name
的字段。那么如何使用Cell.name
字段查询Sample
班级中的cell
?有没有人有这方面的想法?
谢谢!
答案 0 :(得分:1)
有多种方法可以实现这一目标:
qry = session.query(Sample).join(Cell).filter(Cell.name == "a_string")
>> SELECT sample.id AS sample_id, sample.factor_id AS sample_factor_id
>> FROM sample JOIN cell ON cell.id = sample.factor_id
>> WHERE cell.name = :name_1
qry = session.query(Sample).filter(Sample.cell.has(Cell.name == "a_string"))
>> SELECT sample.id AS sample_id, sample.factor_id AS sample_factor_id
>> FROM sample
>> WHERE EXISTS (SELECT 1
>> FROM cell
>> WHERE cell.id = sample.factor_id AND cell.name = :name_1)