Robin  van Leeuwen
Robin van Leeuwen

Reputation: 2703

(Flask)-SQLAlchemy get corresponding model from column

Flask-SQLALchemy i have a model with columns:

class MyModel(db.Model):

    def my_method1(self, arg1):
        pass

    a = Column(String(), primary_key=True)

Now i have a function which accepts Columns as argument to retrieve some information from them:

def get_column_info(column):
    if column.primary_key:
        return True
    else: 
        return False

Note that this is just an example, the get_column_info does much more than that in reality.

Now i want to be able to access the originating model in my get_column_info function. That is i want to be able to call my_method1() from within get_column_info.

Is there a way i can retrieve the originating model from a column instance?

Upvotes: 0

Views: 1257

Answers (1)

Sergey Shubin
Sergey Shubin

Reputation: 3257

There is no proper out of the box method for doing this. Column object has table attribute which returns __table__ attribute of the model but you can't get actual model from it. However (as this answer suggested) you can use get_class_by_table method in sqlalchemy_utils plugin:

from sqlalchemy_utils.functions import get_class_by_table

def get_model(column):
    return get_class_by_table(db.Model, column.__table__)

Upvotes: 2

Related Questions