SQLAlchemy:从表名中获取模型.据我所知,这可能意味着将一些函数附加到元类构造函数

2022-01-20 00:00:00 python sqlalchemy foreign-keys

问题描述

我想创建一个函数,给定一个表名,返回具有该表名的模型.例如:

I want to make a function that, given the name of a table, returns the model with that tablename. Eg:

class Model(Base):
    __tablename__ = 'table'
    ...a bunch of Columns

def getModelFromTableName(tablename):
   ...something magical

所以 getModelFromTableName('table') 应该返回 Model 类.

so getModelFromTableName('table') should return the Model class.

我的目标是在我正在制作的简单表单生成器中使用该函数,因为 FormAlchemy 不适用于 python3.2,我希望它能够很好地处理外键.

My aim is to use the function in a simple form generator I'm making since FormAlchemy does not work with python3.2 and I want it to handle foreign keys nicely.

谁能告诉我如何让 getModelFromTableName 工作?

Can anyone give me any pointers on how to get getModelFromTableName to work?

这是我的一个想法(这可能是完全错误的,我以前没有使用过元类......)

Here's one idea I have (it might be totally wrong, I haven't worked with meta classes before...)

如果我要让我的模型类继承自 Base 以及其他一些类 (TableReg) 并让 TableReg 的类元存储 Model.tablename 在某个全局字典或 Singleton 中.

What if I were to make my Model classes inherit from Base as well as some other class (TableReg) and have the class meta of TableReg store Model.tablename in some global dictionary or Singleton.

我意识到这可能完全关闭,因为 Base 的元类做了一些我不想破坏的非常重要且非常漂亮的东西,但我认为必须有一种方法可以让我附加一点构造函数代码我的模型的元类.或者我不明白.

I realise this could be totally off because Base's metaclass does some very important and totally nifty stuff that I don't want to break, but I assume there has to be a way for me to append a little bit of constructor code to the meta class of my models. Or I don't understand.


解决方案

灵感来自 Eevee 的评论:

def get_class_by_tablename(tablename):
  """Return class reference mapped to table.

  :param tablename: String with name of table.
  :return: Class reference or None.
  """
  for c in Base._decl_class_registry.values():
    if hasattr(c, '__tablename__') and c.__tablename__ == tablename:
      return c

相关文章