使用ORM中的关系查询另一个表的语法?

时间:2012-11-16 04:07:56

标签: database orm sqlalchemy

模型是这样的(在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?有没有人有这方面的想法?

谢谢!

1 个答案:

答案 0 :(得分:1)

有多种方法可以实现这一目标:

1。使用join(...) - 我会在你的情况下选择这个

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

2。使用any / has(...) - 这将使用子查询

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)