简体   繁体   中英

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

I am using the latest ponyorm on Python 3.6.

I want to do some monkey patching on entity classes created at another stage (to add computed fields).

Any chance I can get the list of entities types available from the db object ?

In my models.py file:

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)

In another file:

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

You should be able to obtain subclasses of Entity using the __subclasses__ method.

This example is from Flask SQLAlchemy. Your results should be similar:

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

In your code, you should do the following:

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

In PonyORM Database object has entities property which is a dict of all associated entities:

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

This isn't specific to Pony, but, you can use inspect.getmembers to do this:

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

Basically this will run through all the attributes of the models module and add new_method to any db.Entity subclasses it encounters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM