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

2021-12-02 00:00:00 django database orm oracle

我一直在家里摆弄 Django 和 Django ORM,我不得不说,我觉得它是最好的易用性之一.

I've been messing around with Django and the Django ORM at home, and I've got to say, I feel it is one of the best out there in terms of ease of use.

但是,我想知道是否可以反向"使用它.

However, I was wondering if it was possible to use it in "reverse".

基本上我想做的是从现有的数据库模式(来自一个不使用 django 并且很旧的项目)生成 Django 模型.

Basically what I would like to do is generate Django models from an existing database schema (from a project that doesn't use django and is pretty old).

这可能吗?

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

Update: the database in question is Oracle

推荐答案

是的,使用 inspectdb 命令:

  • http://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb

检查数据库

内省 DATABASE_NAME 设置指向的数据库中的数据库表,并将 Django 模型模块(models.py 文件)输出到标准输出.

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.

如果您有一个要使用 Django 的旧数据库,请使用此选项.该脚本将检查数据库并为其中的每个表创建一个模型.

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.

如您所料,创建的模型将具有表中每个字段的属性.请注意,inspectdb 在其字段名输出中有一些特殊情况:

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:

[...]

相关文章