SQLAlchemy:对外部属性使用like()的filter_by

时间:2011-06-01 17:38:13

标签: python model sqlalchemy foreign-key-relationship

我有以下型号:

class CRRun(Base):
    ...
    crID = Column(u'CR_ID', INTEGER(), ForeignKey(CR.id), primary_key=True,
                  nullable=False)
    cr = relationship(CR, backref=backref("CR_RUN", uselist=False))
    ...

class CR(Base):
    ...
    id = Column(u'CR_ID', INTEGER(), primary_key=True, nullable=False)
    state = Column(u'STATE', VARCHAR(20))
    ...

然后我尝试执行以下操作:

state = 'some value'
crsRuns = Session.query(CRRun)
crsRuns = crsRuns.options(eagerload('cr'))
                 .filter(CRRun.cr != None)
                 .filter(CRRun.cr.state.like('%' + state + '%'))

但是,这会导致以下错误:

  

AttributeError:'InstrumentedAttribute'对象和'Comparator'对象都没有属性'state'

如何通过连接到我通过外键查询的表的表中的列值来过滤查询?

2 个答案:

答案 0 :(得分:3)

尝试:

state = 'some value'
crsRuns = Session.query(CRRun)
crsRuns = crsRuns.options(eagerload('cr')) \
    .filter(CRRun.cr.has(
        CR.state.like('%' + state + '%')
    ))

答案 1 :(得分:1)

我最终做了以下事情:

crsRuns = Session.query(CRRun, CR, Run).join(CR).join(Run)
crsRuns = crsRuns.filter(CR.state.like('%' + state + '%'))