问题描述
我一直在尝试弄清楚如何迭代 SQLAlchemy 模型中定义的列列表.我想要它为几个模型编写一些序列化和复制方法.我不能只是迭代 obj.__dict__
因为它包含很多 SA 特定项目.
I've been trying to figure out how to iterate over the list of columns defined in a SQLAlchemy model. I want it for writing some serialization and copy methods to a couple of models. I can't just iterate over the obj.__dict__
since it contains a lot of SA specific items.
有谁知道从下面获取 id
和 desc
名称的方法吗?
Anyone know of a way to just get the id
and desc
names from the following?
class JobStatus(Base):
__tablename__ = 'jobstatus'
id = Column(Integer, primary_key=True)
desc = Column(Unicode(20))
在这个小案例中,我可以轻松创建一个:
In this small case I could easily create a:
def logme(self):
return {'id': self.id, 'desc': self.desc}
但我更喜欢自动生成 dict
的东西(对于较大的对象).
but I'd prefer something that auto-generates the dict
(for larger objects).
推荐答案
您可以使用以下功能:
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 属性,但不会排除关系.所以基本上它可能会加载依赖项,父母,孩子等,这绝对是不可取的.
It will exclude SA magic attributes, but will not exclude the relations. So basically it might load the dependencies, parents, children etc, which is definitely not desirable.
但实际上要容易得多,因为如果你从 Base
继承,你有一个 __table__
属性,这样你就可以:
But it is actually much easier because if you inherit from Base
, you have a __table__
attribute, so that you can do:
for c in JobStatus.__table__.columns:
print c
for c in JobStatus.__table__.foreign_keys:
print c
请参阅如何从SQLAlchemy 映射对象 - 类似问题.
See How to discover table properties from SQLAlchemy mapped object - similar question.
Mike 请参阅 Mapper.c 和 Mapper.mapped_table.如果使用 0.8 及更高版本,请参阅 Mapper.attrs 和相关函数.
Edit by Mike: Please see functions such as Mapper.c and Mapper.mapped_table. If using 0.8 and higher also see Mapper.attrs and related functions.
Example for Mapper.attrs:
from sqlalchemy import inspect
mapper = inspect(JobStatus)
for column in mapper.attrs:
print column.key
这篇关于迭代sqlalchemy模型定义的列的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!