[Fixed]-How do I generate models for an existing database in Django?

16👍

This is documented on the Django website:

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

$ python manage.py inspectdb

11👍

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.

Leave a comment