SQLAlchemy 将一列的默认值设置为另一列的默认值 [英] SQLAlchemy set default value of one column to that of another column

查看:25
本文介绍了SQLAlchemy 将一列的默认值设置为另一列的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为物质编写一个类,它有一个名称(名称,在实验室中常用)和另一列用于长名称(以防名称实际上不完整).如果没有指定长名称,是否可以告诉类只将名称字段的值复制到长名称字段?

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?

我尝试过这样的事情:

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)

但这失败了,因为 name 是未定义的.还有什么我可以做的吗?

But this fails, since name is undefined. Is there anything else I could do?

推荐答案

您可以创建 上下文敏感的默认函数

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)

这篇关于SQLAlchemy 将一列的默认值设置为另一列的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆