Generating a runtime model using django

I have an application that needs to generate its models at runtime.
This will be done in accordance with the current database schema.
How can I do that?
How can I create classes at runtime in python?
Should I create a json view and save it in the database and then not initialize it to a python object?

+4
source share
3 answers

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

Here is an example of creating a 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

+8
source

You can rely on legacy django database support, which allows you to get 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 classes in a file. Then you can import them on the fly.

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

+2
source

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

Take a look at the source code for the inspectdb management inspectdb . inspectdb "Introspectively scans the database tables in the database pointed to by the NAME parameter and displays the Django model module (models.py file) to standard output."

How can I create classes at 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 version 2.6).

Should I create a json view and save it in the database and then not initialize it to a python object?

That doesn't seem like a good idea to me.

PS: Everyone said that you should really rethink the prerequisites for creating classes at runtime. This is quite extreme for a web application. Just my 2c.

+1
source

All Articles