SQLAlchemy:从表名获取模型。据我所知,这可能意味着将一些函数附加到元类的构造函数中 [英] SQLAlchemy: get Model from table name. This may imply appending some function to a metaclass constructor as far as I can see

查看:162
本文介绍了SQLAlchemy:从表名获取模型。据我所知,这可能意味着将一些函数附加到元类的构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,根据表的名称,返回带有 tablename 的模型。
例如:

  class Model(Base):
__tablename__ ='table'
。 ...一堆列

def getModelFromTableName(tablename):
...不可思议的东西

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

我的目标是在一个简单的表单生成器中使用函数I'因为FormAlchemy不能和python3.2一起工作,所以我希望它很好地处理外键。



任何人都可以给我任何关于如何让getModelFromTableName工作的指针?

这里有一个想法,它可能是完全错误的,我以前没有与元类的工作...)



如果我要使我的模型类继承自基地以及一些其他类(TableReg),并且在某些全局字典或Singleton中具有TableReg store Model tablename 的类元。



我意识到这可能是完全关闭的,因为Base的元类有一些非常重要和非常漂亮的东西,我不想破坏,但是我认为必须有一个方式为我追加一点构造函数代码到我的模型的元类。或者我不明白。

启发来自

$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b $:param tablename:带有表名的字符串
返回类映射到表的引用
$ b:param tablename:带表名的字符串
:返回:类引用或无

为Base._decl_class_registry.values()中的c:
如果hasattr(c,'__tablename__')和c .__ tablename__ ==表名:
返回c


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

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

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.

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...)

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.

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.

解决方案

Inspired by Eevee's comment:

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

这篇关于SQLAlchemy:从表名获取模型。据我所知,这可能意味着将一些函数附加到元类的构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆