[英]Dynamically applied filter on (self-referential) relationship
我有一個要使用過濾器查詢的模型。 我還希望將此過濾器應用於其子級(一對多的自我參照關系)。 例:
class Item(Model):
__tablename__ = 'item'
id = Column(Integer, primary_key=True)
color = Column(String)
parent_id = Column(Integer, ForeignKey('item.id'))
children = relationship(
'Item',
backref=backref('parent', remote_side=[id]),
lazy='dynamic'
)
item = session.query(Item).filter(Item.color == 'blue').one()
現在,我想一次children
集合應用相同的過濾器,並在以后能夠以透明方式訪問過濾后的集合。
我可以想象像這樣的東西:
item.children.apply_filter(Item.color == 'blue') # `children` is dynamic
然后訪問item.children
等同於立即訪問item.children.filter(Item.color == 'blue').all()
。 請注意,使用此解決方案,關系是自引用的事實無關緊要。
SQLAlchemy的API很大,我不知道是否有適當的方法來執行此操作(或等效方法)。
(是否可以在查詢時修改關系的主primaryjoin
?或者給它一個參數?)
請注意,如果您有多個具有相同顏色的項目,則原始查詢item = session.query(Item).filter(Item.color == 'blue').one()
將失敗。
當您通過該操作並獲得(父) Item
實例時:
my_item = session.query(Item).filter(Item.color == 'blue')[0]
# my_item = session.query(Item).filter(Item.color == 'blue').filter(Item.parent == None).one() # assume this is only one root item per color
由於children
是dynamic
,因此my_item.children
將向您返回查詢。 在這種情況下,您只需應用另一個過濾器即可完成:
my_blue_children = my_item.children.filter(Item.color == 'blue').all()
現在, filter
子句將對選擇語句加載子級應用過濾器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.