python - How to get value from SQLAlchemy instance by column name? -
i have table 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 value instance mpttpages column name 'lft'? instance has no attribute lft, left.
inspect instance's mapped class mapping of attribute names columns. if column name matches name you're looking for, attribute name instance.
from sqlalchemy import inspect def getattr_from_column_name(instance, name, default=ellipsis): attr, column in inspect(instance.__class__).c.items(): if column.name == name: return getattr(instance, attr) if default ellipsis: raise keyerror else: return default
Comments
Post a Comment