I have an existing database I'd like to use with Django. Can I create models based on my existing tables?
Answer is "manage.py inspectdb"
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.
This is documented on the Django website:
https://docs.djangoproject.com/en/3.1/howto/legacy-databases/
$ python manage.py inspectdb
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