uralbash
uralbash

Reputation: 3618

How to get value from SQLAlchemy instance by column name?

I have table like this:

class MPTTPages(Base):
    __tablename__ = "mptt_pages"

    parent = None

    id = Column(Integer, primary_key=True)
    left = Column("lft", Integer, nullable=False)
    right = Column("rgt", Integer, nullable=False)

    name = Column(String)
    description = Column(Text)

    visible = Column(Boolean)

    def __repr__(self):
        return "MPTTPages(%s, %d, %d)" % (self.id, self.left, self.right)

How to get value from instance MPTTPages by column name 'lft'? Instance has no attribute lft, just left.

Upvotes: 3

Views: 3776

Answers (1)

davidism
davidism

Reputation: 127410

Inspect the instance's mapped class to get a mapping of attribute names to columns. If a column name matches the name you're looking for, get the attribute name from the instance.

from sqlalchemy import inspect

def getattr_from_column_name(instance, name, default=Ellipsis):
    for attr, column in inspect(instance.__class__).c.items():
        if column.name == name:
            return getattr(instance, attr)

    if default is Ellipsis:
        raise KeyError
    else:
        return default

Upvotes: 7

Related Questions