'Hybrid attribute and relationship error: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with ... has an attribute

I've been following the Working with Relationships section of the Hybrid Attributes SQLAlchemy guide to develop the following:

from sqlalchemy import Column, Integer, select, create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import relationship

Base = declarative_base()


class Parent(Base):

    __tablename__ = "parent"

    id_ = Column(Integer, primary_key=True)
    example_value = Column(Integer)

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


class Child(Base):

    __tablename__ = "child"

    id_ = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent.id_"))

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

    @hybrid_property
    def example_value_check(self):
        if self.parent.example_value == 0:
            return "No"
        elif self.parent.example_value > 0:
            return "Yes"


engine = create_engine("sqlite:///:memory:")
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

session.add(Parent(id_=1, example_value=0))
session.add(Parent(id_=2, example_value=1))
session.add(Child(parent_id=1))
session.add(Child(parent_id=2))
session.commit()

example_value_checks = session.execute(select(Child.example_value_check)).scalars()
print(example_value_checks)

However, I'm getting the following error:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Child.parent has an attribute 'example_value'

From what I can see my case is slightly different because the hybrid_property is in my Child class which also has the foreign key. However, as I'd added the equivalent relationship to the Parent class with back_populates then I figured things would work - which they haven't :(

Where should I go from here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source