0

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?

Robin van Leeuwen
  • 2,625
  • 3
  • 24
  • 35

1 Answers1

2

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__)
Community
  • 1
  • 1
Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
  • Thanks! That was indeed the function that i was looking for, i just implemented that myself according to : http://stackoverflow.com/questions/11668355/sqlalchemy-get-model-from-table-name-this-may-imply-appending-some-function-to – Robin van Leeuwen Dec 14 '16 at 15:09