【问题标题】:Derive a Parent attribute as True if all of its Child attributes are True如果父属性的所有子属性都为真,则将父属性派生为真
【发布时间】:2020-12-28 03:31:56
【问题描述】:
class Parent(Base):
    __tablename__ = "Parent"

    parent_id = Column(Integer, primary_key=True)
    complete = Column(Boolean)

    children = relationship("Child", back_populates="parent")

class Child(Base):
    __tablename__ = "Child"

    child_id = Column(Integer, primary_key=True)
    parent_id = Column(Integer,
                         ForeignKey('Parent.parent_id'))
    complete = Column(Boolean)

    parent = relationship("Parent", back_populates="children",
                            foreign_keys=[parent_id])

我想使用上面的表格,如果所有子完整值都为 True,则父完整布尔值计算为 True,如果任何子完整值为 false,则计算为 False。

【问题讨论】:

    标签: python database postgresql sqlalchemy


    【解决方案1】:

    您不想将completed 声明为“父”表中的真实列,您只需要在Parent 对象中创建一个@hybrid_property

    • 查找不完整的子对象,并
    • 如果找到一个或多个,则返回 False
    class Parent(Base):
        # …
        children = relationship("Child", back_populates="parent")
    
        @hybrid_property
        def completed(self):
            if self.children:
                return not bool([c for c in self.children if not c.completed])
            else:
                return False  # parent has no children
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多