Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate models for an existing database in Django?

I have an existing database I'd like to use with Django. Can I create models based on my existing tables?

like image 738
Nguyễn Tiến Mạnh Avatar asked Jun 02 '16 02:06

Nguyễn Tiến Mạnh


People also ask

What is the Django command to view a database schema of an existing database?

Answer is "manage.py inspectdb"


2 Answers

You can use inspectdb command.

Like this

python manage.py inspectdb Table_Name --database=DataBaseName > filename.py

eg: For specific table from specific database()

python manage.py inspectdb Employee_table --database=db_for_employee > models_file.py

Here db_for_employee exist in DATABASE list in settings.py file.

For specific table in default database:

python manage.py inspectdb Employee_table > models_file.py

For all the tables in default database:

python manage.py inspectdb >models_file.py

This would create a file with name models_file.py at your project level and it would contain the models for the existing database.

Note that the if you don't mention the database name then default database from the settings would be considered.

And if you don't mention the table name then all the tables from the database are considered and you'll find models for all the tables in new models.py file

Needless to say that further you'll have to copy the models or the classes created, to the actual models.py file at the application level.

like image 35
shreesh katti Avatar answered Oct 10 '22 22:10

shreesh katti


This is documented on the Django website:

https://docs.djangoproject.com/en/3.1/howto/legacy-databases/

$ python manage.py inspectdb

like image 146
rrauenza Avatar answered Oct 10 '22 23:10

rrauenza