Delete attribute from SQLAlchemy model object

Viewed 377

I'm trying to delete an attribute from model object that is created on the go, but there seems to be some problem doing so. So, far I've searched through every place including SQLAlchemy documentation and some of its code to find a potential fix but unable to find one.

Below code works fine on python classes but not with a class inherited from 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)

User model

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")

I've also tried deleting the attribute using del but it's doing the same job as delattr, I guess both del and delattr calling the same code under the hood.

I'm totally stumped on this problem and couldn't come up with anything. Any help would be appreciated, Thanks.

1 Answers

So this was expected, as SQLAlchemy ORM mapped objects don't support this particular state for an attribute, that is, attribute doesn't exist and would raise AttributeError. for an ORM mapped class, a mapped attribute always defaults to None and/or empty collection. there's a little bit of an introduction to this here: https://docs.sqlalchemy.org/en/14/tutorial/orm_data_manipulation.html#instances-of-classes-represent-rows

For this particular problem, you can define your column as

localedit = Column('localedit', String,  FetchedValue())

FetchedValue is used when the database is configured to provide some automatic default for a column. So, in this case you only want to ignore the column this would work like a charm. Updated model would look something like:

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id        = Column('id', Integer, primary_key=True)
    localedit = Column('localedit', String,  FetchedValue())
Related