Read time: 3 minutes
Usually, when working with django, we write our models in a file named
models.py
to define the structure of our database/tables i.e. how many
columns will be there and what will be the type of data they will store etc.
Now, I had this case when I was having a database already and I am to create a web-interface to this database through django. And the first thing that came to my mind was how will I connect the existing database with django. As per my experience with Django, I always created the models and django handles the database at the backend. But this time it was somewhat opposite.
Good news! Django reads the existing database that you provide and spits
out the models.py
file without having to write anything. Great, right?
So, let’s get started!
Create the sql dump file for that particular database/table. I am working with a single table so this makes it:
$ mysqldump -u root -p database_name table_name > name_of_sql_dump.sql
Create a database.
$ mysql -u root -p mysql -Bse "CREATE DATABASE database_name";
Or you may login to MySQL first and create the database using:
mysql> CREATE DATABASE database_name;
Import your sql dump file.
$ mysql -u root -p database_name < name_of_sql_dump.sql
In your settings.py file, modify the “DATABASES” part:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database_name',
'USER': 'root',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
And fill the values:
- ‘ENGINE’ is the Database backend you are using. If you are using MySQL, then keep as above. See docs for more.
- ‘NAME’ is the name of the database you created in MySQL.
- ‘USER’ is the name of the MySQL user.
- ‘PASSWORD’ is the password for the MySQL ‘USER’.
- ‘HOST’: default is
localhost
. You can leave it empty. - ‘PORT’: Leave it empty, the default port will be used.
Install MySQL connector/client for Python.
For Python3, you can use:
$ pip install mysqlclient
For Python2, use:
$ pip install MySQL-python
If you get an error like:
fatal error: Python.h: No such file or directory
Install python-dev
$ sudo apt install python-dev
or python3-dev
if using Python3.
Generate models from the database.
$ python manage.py inspectdb >> models.py
It will write the code for models in a file models.py
.
If you are using more than one database in your django project, then specify the database as:
$ python manage.py inspectdb --database=default >> models.py
Here --database
refers to the key of DATABASE dict in the settings.py file
in which we configured the database settings above. The default one is named
default
.
More info: See docs