pythonpostgresqlsqlalchemydateadd

How to offset by 1 year the values of a date column using ORM?


I have an sqlalchemy ORM for a Postgres table:

class Item(Base, BoilerPlateMixinBase):
    id = Column(Integer, primary_key=True)
    date = Column(Date)
    value = Column(Float)

My project performs several SELECT queries on it.
What's the quickest way to experiment having all the dates offset by 1 year?

I could do that by modifying either:

The latter is preferable as it'd require changing just one place in the code.

But how can this be achieved?

(tried DATEADD as suggested here, but didn't work for me. sqlalchemy 2.0)


Solution

  • column_property achieves this by replacing:

        date = Column(Date)
    

    with:

        _date = Column('date', Date)
    
        date = column_property(
            cast(
                _date + text("INTERVAL '1 YEAR'"),
                Date,
            ).label(_date.name)
        )
    

    and it works with leap years as well.