开发者

Runtime model generation using django

开发者 https://www.devze.com 2023-01-18 20:06 出处:网络
I have an application that needs to generate its models on runtime. This will be done according to the current database scheme.

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 repres开发者_如何学JAVAentation and save it in a database and then unserialize it into a python object?


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消