SQLAlchemy set default value of column depending on ID

风流意气都作罢 提交于 2021-01-29 11:33:44

问题


I already know that for general cases: this question is sufficient: SQLAlchemy set default value of one column to that of another column

But when my column depends on the Id column it doesn't work because id is auto generated.

For eg: Using the same example as the other question

class Substance(Base):
    __tablename__ = "substances"
    id = Column(Integer, primary_key=True)
    code = Column(String, unique=True)
    name = Column(String, unique=True)
    subtance_hash = Column(String, unique=True, default=hashgen)

def hashgen(context):
    uid = context.get_current_parameters()['id'] + 100
    name = context.get_current_parameters()['name']
    code = context.get_current_parameters()['code']
    return some_hash_function(uid, name, code)

def some_hash_function(uid, name, code):
    # this is a stupid example for completeness
    return str(uid) + str(name) + str(code) 

The problem here is that uid is None because it will be auto generated while committing the query I think?

So it throws an error:

sqlalchemy.exc.StatementError: (builtins.KeyError) 'id'

Is it even possible to do this? If so how?


回答1:


You can flush your session to set the id before the commit. You can then calculate your hash. You can also use the event system is SQLAlchemy to listen for after_flush events and calculate the hash there. For example:

class Substance(Base):
    __tablename__ = "substances"
    id = Column(Integer, primary_key=True)
    code = Column(String, unique=True)
    name = Column(String, unique=True)
    subtance_hash = Column(String, unique=True)


@event.listens_for(sessionOrSessionFactory, 'after_flush')
def hashgen(session, flush_context):
    for obj in session:
        if isinstance(obj, Substance):
            obj.substance_hash = some_hash_function(obj)


def some_hash_function(obj):
    # this is a stupid example for completeness
    return str(obj.id + 100) + str(obj.name) + str(obj.code)

Another method is to make the hash hybrid_property https://docs.sqlalchemy.org/en/13/orm/extensions/hybrid.html

I haven't played around with hybrid properties much so I will leave it for someone else to contribute an answer for that.



来源:https://stackoverflow.com/questions/59474582/sqlalchemy-set-default-value-of-column-depending-on-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!