3.B] Explain the process of configuring databases and defining models in Django.
Answer:
1. Configuring Databases
To use a database with Django, you need to configure it in the settings.py
file of your Django project. Here’s how you do it:
Specify Database Settings:
- Open the
settings.py
file in your Django project. - Locate the
DATABASES
setting, which is a dictionary defining your database configuration. By default, Django is configured to use SQLite, but you can change this to other databases like PostgreSQL, MySQL, or Oracle. Example configuration for different databases: - SQLite (default):
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } }
- PostgreSQL:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } }
- MySQL:
python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '3306', } }
Install Database Adapter:
- Ensure you have the appropriate database adapter installed.
- For example, for sqlite3 : no adapters needed, for PostgreSQL:
psycopg2
, and for MySQL:mysqlclient
. - Install these via pip:
PostgreSQL:pip install psycopg2-binary, MySQL
:pip install mysqlclient
2. Defining Models
In Django, models define the structure of your database tables. They are represented as Python classes and are stored in the models.py
file of an app.
Create a Model:
- Define a model by creating a class that inherits from
django.db.models.Model
. - Each attribute of the class represents a database field. The field types are defined using Django’s model field classes (e.g.,
CharField
,DateField
,ForeignKey
). Example:
from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): salutation = models.CharField(max_length=10) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() headshot = models.ImageField(upload_to='/tmp') class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) publication_date = models.DateField()
Apply Migrations:
- Create Migrations: Run
python manage.py makemigrations
to create migration files based on your model definitions. This step generates the SQL needed to create or modify database tables. - Apply Migrations: Run
python manage.py migrate
to apply the migrations to the database, creating or updating tables as necessary.
Verify Database Tables:
- To see the SQL statements Django would execute, use
python manage.py sqlmigrate <app_name> <migration_number>
. - To create the tables and indexes in your database, run
python manage.py migrate
. This command will reflect changes to the database schema according to your models.
Additional Notes:
- Default Primary Key: Django automatically adds an integer primary key field named
id
to each model unless specified otherwise. - Many-to-Many Relationships: For fields with many-to-many relationships, Django creates an intermediate table to manage the relationships.