3

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.

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.