Django Database Connectivity

Django supports multiple relational database systems such as SQLite, MySQL, PostgreSQL, and Oracle. By default, Django comes preconfigured to use SQLite, but you can easily configure it to connect to other databases.

There are some Steps for Django Database Connectivity

1. Install Database Driver

To connect to a database like MySQL or PostgreSQL, you need to install the respective driver:

SQLite: No additional installation is required (default).

MySQL: Install mysqlclient:


pip install mysqlclient

PostgreSQL: Install psycopg2


pip install psycopg2

2. Configure the Database in settings.py

Update the DATABASES setting in your settings.py file. The configuration depends on the database engine you’re using.

SQLite (default):


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

MySQL:


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_database_name',
        'USER': 'your_username',
        'PASSWORD': 'your_password',
        'HOST': 'localhost',  # Use '127.0.0.1' or the IP address of your database server
        'PORT': '3306',       # Default MySQL port
    }
}

PostgreSQL:


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database_name',
        'USER': 'your_username',
        'PASSWORD': 'your_password',
        'HOST': 'localhost',  # Use '127.0.0.1' or the IP address of your database server
        'PORT': '5432',       # Default PostgreSQL port
    }
}

3. Create Models

Define your database schema in Django models. Each model corresponds to a database table.


# models.py
from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=100)
    message = models.TextField()  # A large text column

    def __str__(self):
        return self.title

4. Apply Migrations

Django uses migrations to apply model changes to the database.

1. Create Migrations:


python manage.py makemigrations

2. Apply Migrations:


python manage.py migrate

5. Interact with the Database

1. Using the Django Shell: You can interact with the database directly using Django’s ORM (Object-Relational Mapping).


python manage.py shell

# Import the model
from myapp.models import Blog

# Create a new record
blog = Blog(name="How to learn python", message="It's very easy and you can follow my website removeload.com")
blog.save()

# Query records
all_blogs = Blog.objects.all()
print(all_blogs)

# Update a name
blog.name = "Learn Python"
blog.save()

# Delete a record
blog.delete()