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

查看:106
本文介绍了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天全站免登陆