我正在使用SQLalchemy工具处理一个旧版MSSQL数据库,其中我有一个声明性映射。
这个数据库有几个表格有计算列。我可以正常读取,但是(当然)无法写入计算列。但是,当我创建并尝试保存ORM对象时,SQLAlchemy仍然尝试在这些列中保存“None”值,导致错误。
我在网上找到了一些示例,应该使用SQLAlchemy的hybrid_property修饰符将特定列设置为“只读”,但即使实现该修饰符,仍会出现相同的错误(
以下是代码 - 映射:
我希望 hybrid_property 代码可以使计算字段只读,但似乎 SQLAlchemy 仍然尝试根据映射代码在 INSERT 语句中填充它们。(当我查看 SQL 语句时可以看到这一点。我无法发布 SQL 语句,因为我缩写了对象以避免在 StackOverflow 上有任何敏感数据。)
问题是,为什么 SQLAlchemy 仍然尝试插入 tlog_real_timehh、tlog_real_timemm、tlog_real_timess 和 tlog_fin_booking 的值,我如何防止这种情况发生?
谢谢您能给我的任何指针。
Erik
这个数据库有几个表格有计算列。我可以正常读取,但是(当然)无法写入计算列。但是,当我创建并尝试保存ORM对象时,SQLAlchemy仍然尝试在这些列中保存“None”值,导致错误。
我在网上找到了一些示例,应该使用SQLAlchemy的hybrid_property修饰符将特定列设置为“只读”,但即使实现该修饰符,仍会出现相同的错误(
The column "tlog_real_timehh" cannot be modified because it is either a computed column or is the result of a UNION operator.
)。 以下是代码 - 映射:
class transactionlog(Base):
__tablename__ = 'transactionlog'
tlog_id = Column(VARCHAR(length=36), primary_key=True, nullable=False)
tlog_ppl_id = Column(VARCHAR(length=36), ForeignKey('people.ppl_id'))
tlog_evtt_id = Column(VARCHAR(length=5))
tlog_testrun = Column(BIT())
tlog_Data = Column(NVARCHAR(length=300))
tlog_price = Column(DECIMAL(precision=18, scale=2))
tlog_comment = Column(NVARCHAR(length=1000))
_tlog_real_timehh = Column('tlog_real_timehh', INTEGER())
_tlog_real_timemm = Column('tlog_real_timemm', INTEGER())
_tlog_real_timess = Column('tlog_real_timess', INTEGER())
_tlog_fin_booking = Column('tlog_fin_booking', BIT())
@hybrid_property
def tlog_real_timehh(self):
return self._tlog_real_timehh
@tlog_real_timehh.setter
def tlog_real_timehh(self, tlog_real_timehh):
self._tlog_real_timehh = tlog_real_timehh
@hybrid_property
def tlog_real_timemm(self):
return self._tlog_real_timemm
@tlog_real_timemm.setter
def tlog_real_timemm(self, tlog_real_timemm):
self._tlog_real_timemm = tlog_real_timemm
@hybrid_property
def tlog_real_timess(self):
return self._tlog_real_timess
@tlog_real_timess.setter
def tlog_real_timess(self, tlog_real_timess):
self._tlog_real_timess = tlog_real_timess
@hybrid_property
def tlog_fin_booking(self):
return self._tlog_fin_booking
@tlog_fin_booking.setter
def tlog_fin_booking(self, tlog_fin_booking):
self._tlog_fin_booking = tlog_fin_booking
以下为应添加新记录的代码:
rem = Transactionlog()
rem.tlog_testrun = 0
rem.tlog_evtt_id = 'rem'
rem.tlog_Data = None
rem.tlog_comment = 'reminder'
rem.tlog_price = 0
db.session.add(rem)
db.session.flush()
我希望 hybrid_property 代码可以使计算字段只读,但似乎 SQLAlchemy 仍然尝试根据映射代码在 INSERT 语句中填充它们。(当我查看 SQL 语句时可以看到这一点。我无法发布 SQL 语句,因为我缩写了对象以避免在 StackOverflow 上有任何敏感数据。)
问题是,为什么 SQLAlchemy 仍然尝试插入 tlog_real_timehh、tlog_real_timemm、tlog_real_timess 和 tlog_fin_booking 的值,我如何防止这种情况发生?
谢谢您能给我的任何指针。
Erik