Welcome to our deep dive into using MySQL with Django! This tutorial is designed for both beginners and intermediates, so let's get started. π
MySQL is a popular open-source Relational Database Management System (RDBMS), while Django is a high-level Python web framework. In this tutorial, we will learn how to integrate MySQL with Django for your web applications.
Before we dive in, make sure you have MySQL installed on your system. If not, follow the official MySQL installation guide.
Once MySQL is installed, we will install the psycopg2 library, which allows Django to interact with MySQL databases.
pip install psycopg2-binaryπ Note: We will use the psycopg2 library in place of the default PostgreSQL library.
Now, let's configure Django to use MySQL.
Start by creating a new Django project:
django-admin startproject my_django_projectOpen the settings.py file in your project directory and make the following changes:
psychog2:DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
...
}
}'django.db.backends.postgresql' to 'psycopg2':DATABASES = {
'default': {
'ENGINE': 'psycopg2',
'NAME': 'your_database_name',
'USER': 'your_database_user',
'PASSWORD': 'your_database_password',
'HOST': 'localhost',
'PORT': '',
}
}π Note: Replace 'your_database_name', 'your_database_user', and 'your_database_password' with your MySQL database credentials.
Now, create a new app within your project:
python manage.py startapp my_appAfter creating the app, migrate the database to create the necessary tables:
python manage.py makemigrations
python manage.py migrateNow, let's create a simple model and query data from the database.
my_app/models.py π‘from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
def __str__(self):
return self.nameNext, register the model in the admin.py file of your app:
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)Finally, run the server and access the admin site to create and manage instances of your model:
python manage.py runserverNow, open your web browser and navigate to http://127.0.0.1:8000/admin/. You should see your new model listed, and you can create instances of MyModel.
Which library allows Django to interact with MySQL databases?
That's it for this section! In the next part, we will dive deeper into advanced topics like raw SQL queries, managing relationships, and more. Stay tuned! π―