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?

- 18,571
- 25
- 126
- 193
3 Answers
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:
- What is a metaclass in Python?
- http://www.ibm.com/developerworks/linux/library/l-pymeta.html
- http://gnosis.cx/publish/programming/metaclass_1.html

- 1
- 1

- 1,909
- 1
- 15
- 16
-
and how can I generate them based on the database itself? – the_drow Oct 04 '10 at 11:48
-
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 Oct 04 '10 at 13:05
-
Why you want to generate those models at runtime ? what are you trying to do ? – Dominik Szopa Oct 04 '10 at 13:27
-
I'm trying to create some graphical user interface for the models. – the_drow Oct 04 '10 at 17:19
-
What this UI will do ? Will it create just model classes ? or also tables in database ? – Dominik Szopa Oct 04 '10 at 19:03
-
It will also create tables in the database, use south to migrate them, ect. – the_drow Oct 05 '10 at 07:24
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.

- 1,870
- 4
- 26
- 41
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.

- 72,339
- 21
- 134
- 141