Django Database Connectivity
The settings.py file contains all the project settings along with database connection details. By default, Django works with SQLite, database and allows configuring for other databases as well.
Database connectivity requires all the connection details such as database name, user credentials, hostname drive name etc.
To connect with MySQL, django.db.backends.mysql driver is used to establishing a connection between application and database. Let's see an example.
We need to provide all connection details in the settings file. The settings.py file of our project contains the following code for the database.
After providing details, check the connection using the migrate command.
This command will create tables for admin, auth, contenttypes, and sessions. See the example.
Now, access to the MySQL database and see the database from the list of databases. The created database contains the following tables.
Note: It throws an error if database connectivity fails: django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
Well, till here, we have learned to connect Django application to the MySQL database. Next, we will see how to create a table using the model.
Each Django's model is mapped to a table in the database. So after creating a model, we need to migrate it. Let's see an example.
Suppose, we have a model class Employee in the models.py file that contains the following code.
Django first creates a migration file that contains the details of table structure. To create migration use the following command.
The created migration file is located into migrations folder and contains the following code.
Now, migrate to reflect the changes into the database.
Check the database again, now it contains the employee table.
See, a table is present in the database. Well, we have successfully established a connection between our Django application and MySQL database.