在sqlalchemy中对关系使用hybridattribute

2024-06-16 10:50:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让下面这个人为的例子起作用:

class Person(Base):
    __tablename__ = "persons"
    __table_args__ = {"mysql_charset": "utf8mb4"}

    id = Column(Integer, primary_key=True)
    name = Column(String(50), index=True, unique=True)
    birthday = Column(Boolean, default=False)

    @hybrid_property
    def is_birthday_person(self):
        return self.birthday == True

class Party(Base):
    __tablename__ = "parties"
    __table_args__ = {"mysql_charset": "utf8mb4"}

    id = Column(BigInteger, primary_key=True)
    one_id = Column(Integer, ForeignKey("persons.id"))
    two_id = Column(Integer, ForeignKey("persons.id"))

    one_person = relationship("Person", foreign_keys=[one_id])
    two_person = relationship("Person", foreign_keys=[two_id])
    sunshine = Column(Boolean, default=False)

    @hybrid_property
    def everyones_birthday_in_sunshine(self):
        return self.one_person.is_birthday_person and self.two_person.is_birthday_person and self.sunshine 

我试图实现的是过滤所有的聚会,并且只过滤在我运行以下查询时两个人都庆祝生日并且阳光灿烂的聚会:

session.Query(Party).filter(Party.everyones_birthday_in_sunshine).all()

我得到的错误是:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Party.one_person has an attribute 'is_birthday_person'

当我将everyones_birthday_in_sunshine更改为: return self.sunshine == True

它的工作和回报各方在阳光照耀时,我运行:

session.Query(Party).filter(Party.everyones_birthday_in_sunshine).all()

所以问题就出在党和人的关系上,但我不知道怎样才能使它发挥作用

编辑: 当我尝试打印Party中person实例的属性时:everyones_birthday_in_sunshine例如:one_person.name它只打印出Party.one_person。我想肯定是关系问题


Tags: inselfidtrueispartycolumnone