SQLAlchemy 声明类的内省
我正在编写一个小型 sqlalchemy shim,通过一些轻量级数据转换(主要是更改字段名称)从 MySQL 数据库导出数据。我当前的脚本工作正常,但需要我基本上描述我的模型两次 - 一次在类声明中,一次作为要迭代的字段名称列表。
我试图弄清楚如何使用内省来识别作为列访问器的行对象的属性。以下内容几乎完美:
for attr, value in self.__class__.__dict__.iteritems():
if isinstance(value, sqlalchemy.orm.attributes.InstrumentedAttribute):
self.__class__._columns.append(attr)
除了我的多对多关系访问器也是 sqlalchemy.orm.attributes.InstrumentedAttribute 的实例,我需要跳过这些。当我检查班级词典时,有什么方法可以区分两者吗?
我在 sqlalchemy 内省中找到的大多数文档都涉及查看metadata.table,但由于我正在重命名列,因此该数据并不是简单可映射的。
I'm writing a small sqlalchemy shim to export data from a MySQL database with some lightweight data transformations—mostly changing field names. My current script works fine but requires me to essentially describe my model twice—once in the class declaration and once as a list of field names to iterate over.
I'm trying to figure out how to use introspection to identify properties on row-objects that are column accessors. The following works almost perfectly:
for attr, value in self.__class__.__dict__.iteritems():
if isinstance(value, sqlalchemy.orm.attributes.InstrumentedAttribute):
self.__class__._columns.append(attr)
except that my to-many relation accessors are also instances of sqlalchemy.orm.attributes.InstrumentedAttribute, and I need to skip those. Is there any way to distinguish between the two while I am inspecting the class dictionary?
Most of the documentation I'm finding on sqlalchemy introspection involves looking at metadata.table, but since I'm renaming columns, that data isn't trivially mappable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每个映射实体的映射器都有一个包含所有列定义的属性
columns
。例如,如果您有一个声明性类User
,您可以使用User.__mapper__
访问映射器,并使用以下内容访问列:每列都有多个属性,包括
name< /code> (可能与名为
key
的映射属性不同)、nullable
、unique
等等...The Mapper of each mapped entity has an attribute
columns
with all column definitions. For example, if you have a declarative classUser
you can access the mapper withUser.__mapper__
and the columns with:Each column has several attributes, including
name
(which might not be the same as the mapped attribute namedkey
),nullable
,unique
and so on...我仍然希望看到这个问题的答案,但我已经通过名称修改关系访问器(例如“_otherentity”而不是“otherentity”)然后过滤名称来解决这个问题。适合我的目的。
I'd still like to see an answer to this question, but I've worked around it by name-mangling the relationship accessors (e.g. '_otherentity' instead of 'otherentity') and then filtering on the name. Works fine for my purposes.
InstrumentedAttribute
实例有一个名为impl
的属性,实际上它是一个ScalarAttributeImpl
、一个ScalarObjectAttributeImpl
或一个 <代码>CollectionAttributeImpl。我不确定这有多脆弱,但我只是检查它是哪一个,以确定实例最终返回列表还是单个对象。
An
InstrumentedAttribute
instance has an an attribute calledimpl
that is in practice aScalarAttributeImpl
, aScalarObjectAttributeImpl
, or aCollectionAttributeImpl
.I'm not sure how brittle this is, but I just check which one it is to determine whether an instance will ultimately return a list or a single object.