【问题标题】:SQLAlchemy set default value of column depending on IDSQLAlchemy 根据 ID 设置列的默认值
【发布时间】:2020-01-02 19:34:00
【问题描述】:

我已经知道对于一般情况:这个问题就足够了:SQLAlchemy set default value of one column to that of another column

但是当我的列依赖于 Id 列时它不起作用,因为 id 是自动生成的。

例如:使用与其他问题相同的示例

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) 

这里的问题是 uid 是 None 因为它会在我认为提交查询时自动生成?

所以它抛出一个错误:

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

甚至有可能做到这一点吗?如果有怎么办?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    您可以刷新会话以在提交之前设置 id。然后,您可以计算您的哈希值。您还可以使用事件系统 SQLAlchemy 来侦听after_flush 事件并在那里计算哈希值。例如:

    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)
    

    另一种方法是使哈希hybrid_property https://docs.sqlalchemy.org/en/13/orm/extensions/hybrid.html

    我还没有玩过混合属性,所以我会把它留给其他人来提供答案。

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 2018-09-09
      • 2016-08-03
      • 2016-12-22
      • 1970-01-01
      • 2019-06-21
      • 2013-10-30
      • 2022-01-08
      • 2015-10-12
      相关资源
      最近更新 更多