Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to generate django models from the database?

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

like image 772
TM. Avatar asked Jul 24 '09 18:07

TM.


People also ask

Can Django use existing database?

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.

How does Django get data from database?

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.

What is Inspectdb in Django?

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.


2 Answers

Yes, use the inspectdb command:

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

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:

[...]

like image 141
ars Avatar answered Sep 23 '22 01:09

ars


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

like image 38
KKlalala Avatar answered Sep 26 '22 01:09

KKlalala