简体   繁体   English

SQLAlchemy将一列的默认值设置为另一列的默认值

[英]SQLAlchemy set default value of one column to that of another column

I am trying to write a class for substances which has a name filed (for the name, as commonly used in the lab) and another column for the long name (in case the name is actually incomplete). 我正在尝试为具有名称的物质(用于实验室中常用的名称)和长名称的另一列(如果名称实际上不完整)编写一个类。 Is there some wy to tell the class to just copy the value of the name field to the long name field in case a long name is not specified? 是否有一些怀疑告诉班级只是将名称字段的值复制到长名称字段,以防未指定长名称?

I tried something like this: 我试过这样的事情:

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

But this fails, since name is undefined. 但这失败了,因为name未定义。 Is there anything else I could do? 还有什么我能做的吗?

You can create context-sensitive default function 您可以创建上下文相关的默认功能

def mydefault(context):
    return context.get_current_parameters()['name']

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

In addition to rmn's answer if you have more than one column that defaults to value of another one, you can write a helper function to avoid writing many default functions. 除了rmn的答案,如果你有多个列默认为另一个的值,你可以编写一个辅助函数来避免编写许多默认函数。

def same_as(column_name):
    def default_function(context):
        return context.current_parameters.get(column_name)
    return default_function

# or as a one-liner
same_as = lambda col: lambda ctx: ctx.current_parameters.get(col)

class Substance(Base):
    __tablename__ = "substances"
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    long_name = Column(String, unique=True, default=same_as('name'))
    created = Column(DateTime, default=datetime.now)
    edited = Column(DateTime, default=same_as('created'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM