我已使用flask docs中描述的样式声明我的模型,以建立一对多的关系。这些模型嵌套了两次 - 我有带有项目段的文章。
Segments和Items都有一个可见性属性,可以是True或False。编辑时,我只选择所有项目,但在显示时我只想选择能见度属性为True
的项目。
SQLAlchemy中是否有用于过滤子项的习惯用法?我已尝试使用子查询但无法达到我想要的效果。
EG。我想实现:
A single article -> Visible Segment 1 -> This segment's Visible Item 1
-> This segment's Visible Item 2
-> Visible Segment 2 -> This segment's Visible Item 1
-> This segment's Visible Item 2
答案 0 :(得分:2)
如果关系引用少量对象,我通常只在Python中执行此操作:
class Article(Base):
# ...
segments = relationship(Segment)
@property
def visible_items(self):
return [item for segment in self.segments
for item in segment.items
if segment.visible and item.visible]
class Segment(Base):
# ...
items = relationship(Item)
现在,如果你真的想要为此建立完整的关系,你可以定义与该主连接的替代关系:
class Article(Base):
# ...
segments = relationship(Segment)
visible_segments = relationship(Segment,
primaryjoin="and_(Segment.article_id == Article.id, Segment.visible == True)")
@property
def visible_items(self):
return [item for segment in self.visible_segments
for item in segment.visible_items]
class Segment(Base):
# ...
items = relationship(Item)
visible_items = relationship(Item,
primaryjoin="and_(Item.segment_id == Segment.id, Item.visible==True)")