'Persisting a calculated property in SQLAlchemy

Disclaimer: I come from the Django world, and I'm setting out about learning about FastAPI, and it seems SQLAlchemy and alembic are the go to ORM tools for FastAPI.

With Django there is a way on pre_save() to ensure that various calculated properties could be persisted to the database.

Let's say I'm looking at creating a model, called MyCustomModel ... let's also say on that model I have a field called dependent_property:

dependent_property = Column(
        String(
            length=180,
            collation="utf8",
            convert_unicode=False,
            unicode_error=None,
        ),
        index=True
    )

which is, you've guessed it, dependent on some other property of MyCustomModal. It is calculated from two values in the database ...

I want dependent_property to be persisted (for performance) but also to be calculated ... what would be the best way to do this?



Sources

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

Source: Stack Overflow

Solution Source