Is it possible to generate django models from the database?

Solution 1:

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:

[...]

Solution 2:

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