Search code examples
pythonponyorm

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

Solution

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