'SQLAlchemy how to use the same hybrid_property multiple times in a single model

We're migrating from local-time, timestamp fields to UTC datetime fields, adding the new field as <field>_utc while deprecating but continuing to support the old field. We want to populate both fields during INSERT and UPDATE with as few changes to our SQLAlchemy models as possible.

CREATE TABLE Table (
  ...
  ,created_at TIMESTAMP NOT NULL --existing field
  ,created_at_utc DATETIME NULL --new field
  ,updated_at TIMESTAMP NOT NULL
  ,updated_at_utc DATETIME NULL
)

I was hoping to use a hybrid_property to set both DB fields and return either the UTC field or the legacy field when querying. Something like this:

class DateTimeUtcAndLegacy(Base):
    # ...

    created_at_legacy = Column("created_at", Timestamp)
    created_at_utc = Column(Datetime)

    @hybrid_property
    def created_at(self):
        return self.created_at_utc or legacy_to_utc(self.created_at_legacy)

    @created_at.setter
    def created_at(self, value):
        self.created_at_utc = to_utc(value)
        self.created_at_legacy = to_legacy(value)

    @created_at.update_expression
    def created_at(cls, value):
        return [
            (cls.created_at_utc, to_utc(value)),
            (cls.created_at_legacy, to_legacy(value))
        ]

Problem is, I need to use the same property multiple times per table for every legacy datetime I have.

First, is this the best way to go about this?

Second, can I accomplish this with something like __getattr__ __setattr__ magic?



Sources

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

Source: Stack Overflow

Solution Source