I would like to know how to save a calculated value in a clean way in the database:
An example (taken from the SQLAlchemy manual):
Base = declarative_base()
class Interval(Base):
__tablename__ = 'interval'
id = Column(Integer, primary_key=True)
start = Column(Integer)
end = Column(Integer)
@hybrid_property
def length(self):
return self.end - self.start
So length is calculated. But for easier query look-ups (in another database tool), I would like to have this length saved as well into the table.
So my first crude test was to simply add: length = Column(Float). Obviously this doesn't work (but I thought I would try it nevertheless :p) as the length-method overwrites the length-Column.
Right now my only way I can think of is to calculate it in the init & defer to super(), like this:
Base = declarative_base()
class Interval(Base):
__tablename__ = 'interval'
id = Column(Integer, primary_key=True)
start = Column(Integer)
end = Column(Integer)
length = Column(Integer)
def __init__(self, *args, **kwargs):
kwargs['length'] = kwargs['end'] - kwargs['start']
super().__init__(*args, **kwargs)
However, I feel there should be a cleaner way. Is there?
Thanks!