在 SQLAlchemy 中定义表时,如何将函数(依赖于其他列的表达式)定义为列的默认值? [英] How to define a function(expression dependant on other columns) as a default value to a column while defining table in SQLAlchemy?
本文介绍了在 SQLAlchemy 中定义表时,如何将函数(依赖于其他列的表达式)定义为列的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何向SQLAlchemy表中的某列添加一个函数/表达式,该函数/表达式将参数作为其他列作为默认值?例如:我想将 c 定义为 2*x(其他列)的列;它应该保存在数据库中(也可以在其他表中).在这种情况下可以使用@hybrid_property 装饰器吗?
How to add a function/expression which takes arguments as other columns as a default value to a column in the table of SQLAlchemy? For example: I want to define c as a column which is 2*x(other column);which should be saved in the database(could be in other table too). Can @hybrid_property decorator be used in this context?
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)
推荐答案
这是可能的.下面我只是添加了一段代码,你可以试试.更多我认为 this帮助你.
It is possible. Below I'am just adding a piece of code you can try . For more I think this will help you.
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)
这篇关于在 SQLAlchemy 中定义表时,如何将函数(依赖于其他列的表达式)定义为列的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文