我一直试图弄清楚如何迭代 SQLAlchemy 模型中定义的列列表。我想要它为几个模型编写一些序列化和复制方法。我不能只遍历 obj.__dict__
因为它包含很多 SA 特定项目。
有人知道从以下获取 id
和 desc
名称的方法吗?
class JobStatus(Base):
__tablename__ = 'jobstatus'
id = Column(Integer, primary_key=True)
desc = Column(Unicode(20))
在这个小案例中,我可以轻松创建一个:
def logme(self):
return {'id': self.id, 'desc': self.desc}
但我更喜欢自动生成 dict
的东西(对于较大的对象)。
最佳答案
您可以使用以下功能:
def __unicode__(self):
return "[%s(%s)]" % (self.__class__.__name__, ', '.join('%s=%s' % (k, self.__dict__[k]) for k in sorted(self.__dict__) if '_sa_' != k[:4]))
它将排除 SA magic 属性,但不会排除关系。所以基本上它可能会加载依赖项、 parent 、 child 等,这绝对是不可取的。
但实际上要容易得多,因为如果你从 Base
继承,你有一个 __table__
属性,所以你可以这样做:
for c in JobStatus.__table__.columns:
print c
for c in JobStatus.__table__.foreign_keys:
print c
见 How to discover table properties from SQLAlchemy mapped object - 类似的问题。
由 Mike 编辑:请参阅 Mapper.c 等函数和 Mapper.mapped_table .如果使用 0.8 或更高版本,另请参阅 Mapper.attrs及相关功能。
Mapper.attrs 的示例:
from sqlalchemy import inspect
mapper = inspect(JobStatus)
for column in mapper.attrs:
print column.key
关于python - 迭代sqlalchemy模型的定义列的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2537471/