Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在SQLAlchemy中定义表时,如何将函数(表达式依赖于其他列)定义为列的默认值?_Python_Python 3.x_Sqlite_Sqlalchemy_Flask Sqlalchemy - Fatal编程技术网

Python 在SQLAlchemy中定义表时,如何将函数(表达式依赖于其他列)定义为列的默认值?

Python 在SQLAlchemy中定义表时,如何将函数(表达式依赖于其他列)定义为列的默认值?,python,python-3.x,sqlite,sqlalchemy,flask-sqlalchemy,Python,Python 3.x,Sqlite,Sqlalchemy,Flask Sqlalchemy,如何将参数作为其他列作为默认值添加到SQLAlchemy表中的列中的函数/表达式?例如:我想将c定义为一个2*x的列(另一列);应该保存在数据库中(也可以保存在其他表中)。@hybrid_property decorator可以在这种情况下使用吗 from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Sess

如何将参数作为其他列作为默认值添加到SQLAlchemy表中的列中的函数/表达式?例如:我想将c定义为一个2*x的列(另一列);应该保存在数据库中(也可以保存在其他表中)。@hybrid_property decorator可以在这种情况下使用吗

from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, aliased
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.orm import sessionmaker


engine = create_engine('sqlite:///Helloworld.db', echo=False)
Session = sessionmaker(bind=engine)
metadata = MetaData(engine)
Base = declarative_base()

class HelloWorld(Base):
    __tablename__ = 'helloworld'
    pm_key = Column(Integer, primary_key=True)
    x = Column(Integer, nullable=False)
    c = Column(Integer,default=2*x)

Base.metadata.create_all(engine)

这是可能的。下面我只是添加了一段代码,你可以试试。我想更多的东西会对你有帮助

def mydefault(context):
    return context.current_parameters.get('X')

class HelloWorld(Base):
    __tablename__ = 'helloworld'
    pm_key = Column(Integer, primary_key=True)
    x = Column(Integer, nullable=False)
    c = Column(Integer,default=mydefault)

这有帮助!感谢您如何将此新列(c)转换为可变列?@Apurva要制作可变列,在sqlalchemy中有一个选项,如
column(MutableDict.as_mutable(PickleType))
。我提到一位推荐人,因为我不知道你到底在找什么。你可以通过它,你可以与我们分享你的疑问:)因此,我在这里需要的是一个列,它依赖于其他列,它应该是可变的,也就是说,如果我在将来将表达式更改为3*x;应发出所有更改,并且所有以前保存的数据都应受到此影响。