python - SQLAlchemy - how to get hybrid attributemethod returns a different type - Stack Overflow

admin2025-04-17  1

Say I have a student who completes exams.

class Exams(Base):
    __tablename__ = 'questions'
    idx: Mapped[int] = mapped_column(primary_key=True)
    passed: Mapped["bool"] = mapped_column()
    student: Mapped["student"] = relationship(back_populates="student")
    student_id: Mapped[int] = mapped_column(ForeignKey("student.idx"))


class Student(Base):
    __tablename__ = 'homework'
    idx: Mapped[int] = mapped_column(primary_key=True)
    answered_correctly: Mapped["bool"] = mapped_column()
    exams: Mapped[list["Exams"]] = relationship(
        back_populates="student", default_factory=list
    )

    @hybrid_property
    def passed_exams(self) -> list[exams]:
        return all([exams for exam in self.exams if exam.passed])

I want to use the hybrid property in queries like so:

stmt = select(Student.passed_exams).where(Student.name == 'Joe Bloggs')

The query here is simple & could be achieved with a different query - however, if Exam has more complex attributes like different subjects & completion dates, I want to be able to capture that in a hybrid property/method.

In order to use the hybrid property in queries, I need to implement inplace.expression. From what I understand, the expression should return the WHERE clause criteria that returns the desired rows. But in this case, I want to select on a different table than the one belonging to the hybrid property.

How can I get the hybrid property to work? Or am I misunderstanding how property is supposed to work?

转载请注明原文地址:http://anycun.com/QandA/1744884213a88987.html