如何列出 db 对象中的所有实体类型?

How do I list all entity types from the db object?

我在 Python 3.6.

上使用最新的 ponyorm

我想对在另一个阶段创建的实体 类 进行一些猴子修补(以添加计算字段)。

我是否有机会从 db 对象中获得可用的实体类型列表?

在我的 models.py 文件中:

from pony.orm import *
db = Database()

class OneEntity(db.Entity):
    id = PrimaryKey(int, auto=True)
    nom = Required(str)

class AnotherEntity(db.Entity):
    id = PrimaryKey(int, auto=True)
    someprop = Required(str)

在另一个文件中:

from models import *
db.bind(provider='sqlite', filename = 'test.db', create_db = True)
db.generate_mapping(create_tables = True)

def say_hello():
    """ some dummy proc to monkey patch onto entity classes"""
    print("hello")

#This works, but isn't workable for my use case (too many entity classes)
OneEntity.monkey_patched_method = say_hello


#And here I'd like to have the ability to list entity classes programmatically

for Entity in some_code_that_i_dont_know :
    Entity.new_method = say_hello

这不是 Pony 特有的,但是,您可以使用 inspect.getmembers 来执行此操作:

import inspect
import models


for name, attr in inspect.getmembers(models):
    if inspect.isclass(attr) and issubclass(attr, db.Entity:
        models.__dict__[name].new_method = say_hello

基本上,这将 运行 遍历 models 模块的所有属性,并将 new_method 添加到它遇到的任何 db.Entity 子类。

您应该能够使用 __subclasses__ 方法获得 Entity 的子类。

这个例子来自 Flask SQLAlchemy。您的结果应该类似:

>>> db.Model.__subclasses__()                                                                                                                               
[myapp.models.User,
 myapp.models.Organization,
 myapp.models.Customer,
 myapp.models.Address,
 ...
]

在您的代码中,您应该执行以下操作:

for Entity in db.Entity.__subclasses__():
    Entity.new_method = say_hello

在 PonyORM 中 Database 对象有 entities 属性 这是所有关联实体的字典:

for entity_name, entity_cls in db.entities.items():
    print(entity_name)