我有这样的表:
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)
如何通过列名'lft'从实例MPTTPages获取值?实例没有属性lft,就在左边。
答案 0 :(得分:4)
检查实例的映射类,以获取属性名称到列的映射。如果列名与您要查找的名称匹配,请从实例中获取属性名称。
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