是否可以从数据库生成 django 模型?

我一直在家里使用 Django 和 Django ORM,我不得不说,我觉得它在易用性方面是最好的之一。

然而,我想知道是否有可能使用它在“反向”。

基本上,我想做的是从现有的数据库模式(从一个不使用 Django 并且相当老的项目)生成 Django 模型。

这可能吗?

更新: 有问题的数据库是 Oracle

63590 次浏览

Yes, use the inspectdb command:

inspectdb

Introspects the database tables in the database pointed-to by the DATABASE_NAME setting and outputs a Django model module (a models.py file) to standard output.

Use this if you have a legacy database with which you'd like to use Django. The script will inspect the database and create a model for each table within it.

As you might expect, the created models will have an attribute for every field in the table. Note that inspectdb has a few special cases in its field-name output:

[...]

(Django 1.7.1) Simply running python manage.py inspectdb will create classes for all tables in database and display on console.

 $ python manage.py inspectdb

Save this as a file by using standard Unix output redirection:

 $ python manage.py inspectdb > models.py

(This works for me with mysql and django 1.9)

I have made a reusable app based on django's inspectdb command utility, Django Inspectdb Refactor.

This breaks models into different files inside models folder from a existing database. This helps managing models when they become large in number.

You can install it via pip:

pip install django-inspectdb-refactor

Then register the app in settings.py as inspectdb_refactor

After this you can use it from command line as :

python manage.py inspectdb_refactor --database=your_dbname_defined_in_settings --app=your_app_label

This will successfully create models folder with all the tables as different model files inside your app. For example:

typical structure

More details can be found here.