【问题标题】:Delete attribute from SQLAlchemy model object从 SQLAlchemy 模型对象中删除属性
【发布时间】:2021-08-27 10:23:40
【问题描述】:

我正在尝试从在旅途中创建的模型对象中删除一个属性,但这样做似乎有一些问题。所以,到目前为止,我已经搜索了所有地方,包括 SQLAlchemy 文档和它的一些代码,以找到潜在的修复方法,但找不到。

以下代码适用于 python 类,但不适用于继承自 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 做的工作相同,我猜deldelattr 在后台调用相同的代码。

我完全被这个问题难住了,想不出任何办法。 任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python python-3.x sqlalchemy orm


    【解决方案1】:

    所以这是意料之中的,因为 SQLAlchemy ORM 映射对象不支持属性的这种特定状态,也就是说,属性不存在并且会引发 AttributeError。对于 ORM 映射类,映射属性始终默认为 None 和/或空集合。这里有一点介绍: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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      相关资源
      最近更新 更多