我正在使用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
答案 0 :(得分:1)
您应该能够使用Entity
方法获得__subclasses__
的子类。
此示例来自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
答案 1 :(得分:1)
在PonyORM中,Database
对象具有entities
属性,该属性是所有关联实体的命令:
for entity_name, entity_cls in db.entities.items():
print(entity_name)
答案 2 :(得分:0)
这不是Pony特有的,但是您可以使用inspect.getmembers
来做到这一点:
WHERE word LIKE '%KG%' AND word NOT LIKE '%[A-Z]KG[A-Z]%'
基本上,这将遍历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
子类中。