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
In order to use an existing database in Django, you need to have a model for each table. Creating models for existing tables manually is just too much work. However, there's no need to do that, since Django has a builtin tool to solve this exact problem.
The database view is created by following the SQL and it can be injected into a customized data migration with the raw SQL execution command. The next step is to create a Django model which maps to this view so we can use Django ORM to retrieve the data from the view.
Django comes with a utility called inspectdb that can create models by introspecting an existing database. You can view the output by running this command: $ python manage.py inspectdb. Save this as a file by using standard Unix output redirection: $ python manage.py inspectdb > models.py.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With