0

模型是这样的(在 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.nameSample课堂上查询cell字段呢?有人对此有想法吗?

谢谢!

4

1 回答 1

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)
于 2012-11-16T09:30:07.367 回答