Mapping a class against multiple tables in SQLAlchemy
Regarding the KeyError
: The strings that are printed in the repr
of the __table__.columns
object are NOT the keys, and because you have multiple id
columns there is some name munging going on. You probably want to do "persons_id"
rather than "persons.id"
but I recommend printing __table__.columns.keys()
to be sure.
Regarding the AttributeError
: SQLAlchemy maps column names directly to attributes by default, unless you define attribute mappings yourself, which you are. The fact that you are defining the id
attribute as a column_property
on persons.c.id, users.c.id, user_groups.c.user_id
means that none of those columns is being directly mapped to an attribute on the ORM class anymore, but they will still be in the columns
collection. So you just can't use columns
as an iterable of attribute names.
I did not reproduce all of your code/data, but I put together a simpler test case with 3 tables (including a m2m relationship) to verify these items.