101

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".

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).

Is this possible?

Update: the database in question is Oracle

Cœur
  • 37,241
  • 25
  • 195
  • 267
TM.
  • 108,298
  • 33
  • 122
  • 127

3 Answers3

112

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:

[...]

Community
  • 1
  • 1
ars
  • 120,335
  • 23
  • 147
  • 134
  • 1
    Reading over that info, it says it is supported for mysql, sqlite, and postgresql. Sadly the database I am trying to use is Oracle :( – TM. Jul 24 '09 at 19:01
  • oof, I don't believe Django has good support for Oracle at the moment, both forwards or backwards : / – AlbertoPL Jul 24 '09 at 19:04
  • 5
    Django has almost all the features one could think of. It still amazes me even after years of use. – Divick Feb 11 '16 at 04:02
  • I'm not sure but... maybe you should point out that the link refers to the `dev` version (with more emphasize ?? maybe not..) – Karmavil Jul 02 '18 at 21:57
  • is it possible to use same command when new table is inserted – selvakumar Dec 06 '18 at 10:09
38

(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)

Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90
KKlalala
  • 965
  • 1
  • 13
  • 23
12

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.

not2acoder
  • 1,142
  • 11
  • 17