簡體   English   中英

語法使用ORM中的關系查詢另一個表?

[英]syntax to query another table using relationship in ORM?

該模型是這樣的(在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'

似乎Sample類中的cell字段沒有名為name的字段。 然后,如何在帶有cell字段的Sample類中查詢Cell.name 有人對此有想法嗎?

謝謝!

有多種方法可以實現:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM