从 SQLAlchemy 模型对象中删除属性
Delete attribute from SQLAlchemy model object
我正在尝试从移动中创建的模型对象中删除一个属性,但这样做似乎有些问题。所以,到目前为止,我已经搜索了每个地方,包括 SQLAlchemy 文档和它的一些代码,以找到一个潜在的修复但无法找到一个。
下面的代码在 python classes 上工作正常,但不适用于从 declarative_base
继承的 class
for row in data:
model_obj = DBEngine.models.User()
[setattr(model_obj, key, value) for key, value in row.items()]
# below line doesn't work as expected, instead of deleting the
# attribute it just sets the value of attribute to None
delattr(model_obj, 'localedit')
session.add(model_obj)
用户模型
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column('id', Integer, primary_key=True)
localedit = Column('localedit', String, default="0000-00-00 00:00:00")
我也试过使用 del
删除该属性,但它与 delattr
做同样的工作,我猜 del
和 delattr
调用相同的代码在引擎盖下。
我完全被这个问题难住了,什么也想不出来。
任何帮助将不胜感激,谢谢。
所以这是预料之中的,因为 SQLAlchemy ORM 映射对象不支持属性的这种特定状态,即属性不存在并且会引发 AttributeError。对于 ORM 映射 class,映射属性始终默认为 None and/or 空集合。这里有一些介绍:https://docs.sqlalchemy.org/en/14/tutorial/orm_data_manipulation.html#instances-of-classes-represent-rows
对于这个特定问题,您可以将列定义为
localedit = Column('localedit', String, FetchedValue())
当数据库配置为为列提供一些自动默认值时,使用 FetchedValue。因此,在这种情况下,您只想忽略这会很有用的列。更新后的模型看起来像:
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column('id', Integer, primary_key=True)
localedit = Column('localedit', String, FetchedValue())
我正在尝试从移动中创建的模型对象中删除一个属性,但这样做似乎有些问题。所以,到目前为止,我已经搜索了每个地方,包括 SQLAlchemy 文档和它的一些代码,以找到一个潜在的修复但无法找到一个。
下面的代码在 python classes 上工作正常,但不适用于从 declarative_base
for row in data:
model_obj = DBEngine.models.User()
[setattr(model_obj, key, value) for key, value in row.items()]
# below line doesn't work as expected, instead of deleting the
# attribute it just sets the value of attribute to None
delattr(model_obj, 'localedit')
session.add(model_obj)
用户模型
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column('id', Integer, primary_key=True)
localedit = Column('localedit', String, default="0000-00-00 00:00:00")
我也试过使用 del
删除该属性,但它与 delattr
做同样的工作,我猜 del
和 delattr
调用相同的代码在引擎盖下。
我完全被这个问题难住了,什么也想不出来。 任何帮助将不胜感激,谢谢。
所以这是预料之中的,因为 SQLAlchemy ORM 映射对象不支持属性的这种特定状态,即属性不存在并且会引发 AttributeError。对于 ORM 映射 class,映射属性始终默认为 None and/or 空集合。这里有一些介绍:https://docs.sqlalchemy.org/en/14/tutorial/orm_data_manipulation.html#instances-of-classes-represent-rows
对于这个特定问题,您可以将列定义为
localedit = Column('localedit', String, FetchedValue())
当数据库配置为为列提供一些自动默认值时,使用 FetchedValue。因此,在这种情况下,您只想忽略这会很有用的列。更新后的模型看起来像:
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column('id', Integer, primary_key=True)
localedit = Column('localedit', String, FetchedValue())