How to use django with an existing database (mysql)
In this short tutorial, I’ll share with you how to connect Django to an existing MySQL database.
First , i would like you to know this is not meant for pure beginners, if you’ve used Django with sqlite before, were good to go.
Make sure you have mysqlclient installed, if not, run the commands below:
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential (for debian) or sudo yum install python3-devel mysql-devel (for redhat or centos)
pip3 install mysqlclient
You can read more about mysqlclient on the official website here
Just a few steps.
- Create a django project in the usual way
django-admin startproject mysite
2. Move to the mysite directory using the command below
cd mysite
3. Create an app inside your project root directory, you can use either of the following commands:
django-admin startapp myapp
or
python3 manage.py startapp myapp
Note, i used python3 because that’s what’s installed on my pc
4. Edit the settings.py as follows:
- add myapp to the installed apps
- change the database parameters
Refer to the screenshots below:
By default, django uses sqlite which uses django.db.backends.sqlite engine. I have replaced the engine with mysql engine as you can see in the screenshot above.
5. Test whether you can connect to your database using this command:
python3 manage.py dbshell
if you see any errors, just google the solution over the internet
6. Now add the database tables to your models. Many tutorials will be half baked, but be keen here, so be careful, but you’re safe here
Django comes with the inspectdb command which checks on the structure of your database and converts its into python code in your models.py.
python3 manage.py inspectdb >myapp/models.py
Warning
python3 manage.py inspectdb >models.py will not work
As you already know, manage.py is used to run all django related commands such as runserver, createsuperuser, makemigrations, migrate, inspectdb etc. each command plays a specific role.
The command inspectdb we used above maps the database structure to the file ‘models.py’ which is located in the directory ‘myapp’. Remember, every django application exists in its own directory.
Now open your models.py and see the magic that happened.
There are some notes in the comment section at the beginning of the file, do what the comment says
Instead of struggling to write your models, you can now simple design your database using workbench or on the browser via the phpmyadmin and just map it to your models
Enjoy your coding, see you next time.