views:

59

answers:

3

I have an application that needs to generate its models on runtime.
This will be done according to the current database scheme.
How can it be done?
How can I create classes on runtime in python?
Should I create a json representation and save it in a database and then unserialize it into a python object?

A: 

I have an application that needs to generate its models on runtime.

Take a look at the source code for the inspectdb management command. Inspectdb "Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output."

How can I create classes on runtime in python?

One way to do this is to use the functions provided by the new module (this module has been deprecated in favor of types since 2.6).

Should I create a json representation and save it in a database and then unserialize it into a python object?

This doesn't sound like a good idea to me.

PS: All said you ought to really rethink the premise for creating classes at runtime. It seems rather extreme for a web application. Just my 2c.

Manoj Govindan
+5  A: 

You can try to read this http://code.djangoproject.com/wiki/DynamicModels

Here is example how to create python model class:

Person = type('Person', (models.Model,), {
    'first_name': models.CharField(max_length=255),
    'last_name': models.CharField(max_length=255),
})

You can also read about python meta classes:
- http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
- http://www.ibm.com/developerworks/linux/library/l-pymeta.html
- http://gnosis.cx/publish/programming/metaclass_1.html

Dominik Szopa
and how can I generate them based on the database itself?
the_drow
You would have to look at code of inspectdb, and based on that create model classes for each table. http://code.djangoproject.com/svn/django/trunk/django/core/management/commands/inspectdb.py
Dominik Szopa
Why you want to generate those models at runtime ? what are you trying to do ?
Dominik Szopa
I'm trying to create some graphical user interface for the models.
the_drow
What this UI will do ? Will it create just model classes ? or also tables in database ?
Dominik Szopa
It will also create tables in the database, use south to migrate them, ect.
the_drow
+1  A: 

You could base yourself on the legacy database support of django which allows you to obtain django models from the definitions found in the database :

See here : http://docs.djangoproject.com/en/dev/howto/legacy-databases/?from=olddocs

In particular,

manage.py inspectdb 

allows you to create the classes in a file. You should then be able to import them on the fly.

That said, it seems to me that you are on a risky path by doing this.

madewulf