SQLAlchemy Introspection of declarative classes

I am writing a small sqlalchemy shim to export data from a MySQL database with some easy data transformations - basically changing field names. My current script works fine, but requires me to describe my model twice - once in the class declaration and once as a list of field names to repeat.

I am trying to figure out how to use introspection to identify the properties of row objects that are column assemblers. 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-many accessors relationships are also instances of sqlalchemy.orm.attributes.InstrumentedAttribute, and I need to skip them. Is there a way to distinguish between the two while I check the class dictionary?

Most of the documentation I find in the sqlalchemy introspection includes looking at .table metadata, but since I am renaming columns, this data is not trivially accessible.

+7
python introspection declarative sqlalchemy
source share
3 answers

I would still like to get an answer to this question, but I worked on it by creating relationship attributes (for example, "_otherentity" instead of "otherentity") and then filtering the name. Works great for my purposes.

+1
source share

The Mapper of each displayed object has a columns attribute with all column definitions. For example, if you have a declarative User class, you can access the collector with User.__mapper__ and columns with:

 list(User.__mapper__.columns) 

Each column has several attributes, including name (which may not be the same as the associated attribute with the name key ), nullable , unique , etc.

+7
source share

The InstrumentedAttribute instance has an impl attribute, which in practice is a ScalarAttributeImpl , a ScalarObjectAttributeImpl or CollectionAttributeImpl .

I'm not sure how fragile this is, but I'm just checking which one it should determine if the instance will return a list or a single object.

+1
source share

All Articles