Skip to content
Advertisement

PonyORM Database Table Dynamic Definition

As far as I know from the research I’ve made, the typical way of defining a table using PonyORM in Python is like the following:

from pony.orm import *
db = Database()
# Database connection ...
class SampleTable(db.entity):
    sample_int_field = Required(int)
    sample_string_field = Required(str)
    # ...
db.generate_mapping(create_tables=True)

My Problem: this uses db.entity

I wish to define a table without using the specific Databse instance in an abstract general manner, and connect it to the instance when I need to.

is there a way to do so?

concept (not real runnable code presumably):

# SampleAbstractTable.py

from pony.orm import *
class SampleAbstractTable(Database):  
    sample_int_field = Required(int)
    sample_string_field = Required(str)
    # ...

# main.py

from pony.orm import *
import SampleAbstractTable
db = Database()
# Database connection ...
db.connectTables((SampleAbstractTable.SampleAbstractTable, ...))
db.generate_mapping(create_tables=True)

EDIT:

One idea I have is to create a wrapper class for the database I wish to use with a certain group of tables, and define the tables in the init, because the whole point of me wishing to define tables dynamically is to seperate the Database instance creation from the table classes’ definitions, namely:

from pony.orm import *
class sampleDatabase:
    def __init__(self):
        self._db = Database()
        # Database connection ...
        class TableA(db.entity):
            # ...
        class TableB(db.entity):
            # ...
        self._db.generate_mapping(create_tables=True)

but then I have issues in accessing the database tables…

Advertisement

Answer

First of all you’re working with Entities, not Tables. They’re not the same thing.

Your problem can be solved just defining the function like factory

def define_entities(db):
    class Entity1(db.Entity):
        attr1 = Required(str)
        ... and so on

And then later when you create your Database instance you just call

db = Database(...)
define_entities(db)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement