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

2023-08-30Python开发问题
26

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

问题描述

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

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

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11