How to find AssociationProxy declared_attr name in SQLAlchemy from inspection with all_orm_descriptors

320 Views Asked by At

I have a SQLAlchemy table class that has an association proxy defined (through a mixin) as below:

@declared_attr
def nationality_name(self):
    return association_proxy("nationality", "name")

I would like to get the name of this attribute using the SQLAlchemy inspection methods. I've tried the following:

for column in mapper.all_orm_descriptors:
    print(column.key)

but this gives the name of the the assocation proxy as _AssociationProxy_nationality_4587917712, not the name that I actually gave it, which was nationality_name. I can't seem to find any other attributes that I could use to get the name it's actually been given.

Is there a way to get this name through SQLAlchemy inspection?

It would probably be possible to fall back on just using dir on the table class, but that seems rather fragile (and I'd have to filter out all of the attributes of the class that aren't column names or association proxies).

In searching StackOverflow, I've found this question where someone says "I worked around it by getting the name of the proxy, and then using getattr" - but I don't know how they got the name. Possibly they weren't using a declared_attr, which might be making this more complicated.

0

There are 0 best solutions below