Compute the value of a column based on other columns in SQLAlchemy?

Viewed 1386

I am using SQLAlchemy as an ORM in a Python codebase to be able to connect with a MySQL db. I want to be able to automatically calculate and insert a value in a column based on the values in other columns of the same row.

This is what my class looks like:

class SentNotification(Base):
    __tablename__ = 'sent_notification'

    campaign = Column(VARCHAR(34), nullable=False)
    alert_type = Column(VARCHAR(34), nullable=False)
    identifier = Column(VARCHAR(34), nullable=False)
    message_params = Column(JSON, nullable=True)
    send_time = Column(Integer, nullable=False)
    nonce = Column(VARCHAR(32), nullable=False, primary_key=True)

The nonce column is supposed to be an md5 hash (or any other custom function) of campaign, alert_type, identifier and message_params (json dump).

I can obviously calculate this separately and call SentNotification with the nonce but it would be much more cleaner if I could only pass in the first 5 values and my class would automatically take care of the calculation and insertion of the nonce.

Note: I do not want to use hybrid property since that calculates the value and I want to actually persist the nonce in the database.

0 Answers
Related