Search code examples
sqlalchemy

using column_property with SqlAlchemy and Oracle DB


I need to create a virtual column in my sqlalchemy model that can be loaded along with all other column-mapped attributes at load time. SQLAlchemy docs shows how, using column_property().

This works for simple string concatenation but if I need to use a method I get an error

Error while fetching my payments: (oracledb.exceptions.NotSupportedError) DPY-3002: Python value of type "function" is not supported

My method calculates a time based on certain mapped column values. I want to use that time value in my virtual column. Is there anyway to do this using column_property?

code example:

freq: Mapped[str] = mapped_column(String(10), nullable=True)
time = column_property(?)

def time(self) -> str:
        if self.freq == <value>:
            return <calculated_value_1>
        elif self.freq == <other_value>:
            return <calculated_value_2>
        elif self.freq == <yet_another_value>:
            return <calculated_value_3>

Solution

  • I was able to make it work using column_property and hybrid_attributes. Because I only need it for db queries I kept it as a column_property.

    example with column_property:

    time = column_property(case(expression))
    

    example with hybrid attributes:

    @hybrid_property
    def time(self) -> str:
            if self.freq == <value>:
                return <calculated_value_1>
            elif self.freq == <other_value>:
                return <calculated_value_2>
            elif self.freq == <yet_another_value>:
                return <calculated_value_3>
    
    @period.expression
    def time(cls) -> str:
            return case(expression)