Django Database Configuration Guide
Django Database Configuration Guide
● Django provides built-in support for database operations, making it easier to manage
data without writing SQL queries directly. It uses the Object-Relational Mapping
(ORM) approach to map model classes to database tables.
● Django models define the structure of your database tables using Python classes. Each
model class represents a table in the database, and its attributes define the columns.
● SQLite3 is the default database used by Django, which is suitable for small-scale
applications.
● For larger applications, you may need to configure other relational databases like
MySQL, PostgreSQL, or Oracle.
DATABASES = {
'default': {
'ENGINE': '[Link].sqlite3',
● You can change the database engine to MySQL, PostgreSQL, or Oracle. Here
are the configurations:
1. MySQL Configuration:
DATABASES = {
'default': {
'ENGINE': '[Link]',
'NAME': 'employeedb',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
DATABASES = {
'default': {
'ENGINE': '[Link]',
'NAME': 'employeedb',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
DATABASES = {
'default': {
'ENGINE': '[Link]',
'NAME': 'XE',
'USER': 'system',
'PASSWORD': 'system',
'HOST': 'localhost',
'PORT': '1521',
● Run the following command to validate the project setup, including database
connectivity.
● In Django, models are Python classes that define the structure of your database tables.
Each model class corresponds to a table, and the attributes represent the table
columns.
Example: DBProject
● Create a new project called DBProject inside the workspace (by activating the virtual
environment)
cd DBProject
Defining a Model:
● We have to write all the model classes for an application inside the '[Link]'
file for that particular application folder.
class Student([Link]):
roll = [Link](unique=True)
name = [Link](max_length=100)
age = [Link]()
email = [Link](unique=True)
address = [Link]()
phone_number = [Link](max_length=15,
unique=True)
admission_date = [Link](auto_now_add=True)
is_active = [Link](default=True)
def __str__(self):
return [Link]
Explanation:
● The above Model class will be converted into the database table.
● For the above Model class the corresponding table name will be generated in
the following format inside the database:
appname_modelclassname
Example:
StudentApp_student
● To convert your model definitions into actual database tables, Django uses migrations.
Creating Migrations:
python [Link] makemigrations
● The above command generates migration files that describe the changes in the
database schema (e.g., creating tables).
● Inside the app\migrations\ folder a new file will be created with the name
"0001_initial.py"
Applying Migrations:
● With the above command all the installed app related database tables will be created
along with our application related database tables inside the “db.sqlite3” database.
‘id’ field:
1. For every table django will generate a special column named with "id".
2. id is a primary key.(unique value for every record)
3. It is an auto increment field. While inserting data we are not required to provide value
for this field.
4. This field is of type: BigAutoFeild
5. We can override the behaviour of the id field and we can make our own field as id.
6. Every column is by default not null.
Note: to make the roll as the primary key: use the following way:
roll = [Link](primary_key=True)
Summary:
● Purpose: Detects changes in your model definitions (e.g., adding a field, modifying a
model) and generates migration files that describe those changes.
● Output: Creates Python files (e.g., 0001_initial.py) in the migrations/ directory of your
app. These files contain instructions for altering the database schema.
● Effect: Does not modify the database—it only prepares the migration plan.
● Example: If you add a grade field to the Student model, makemigrations generates a
migration file to add that column.
● Purpose: Applies the migration files to the database, executing the SQL commands to
create, update, or delete tables/columns as needed.
● Effect: Updates the actual database schema and creates/updates tables (e.g.,
testapp_student).
● Example: Running migrate after makemigrations will add the grade column to the
testapp_student table in the database.
Key Difference: makemigrations is about planning changes, while migrate is about executing
those changes.
● In addition to our application tables, default application tables also will be created.
[Link]
username: ratan
email: ratan@[Link]
password: 123
Now we can access the admin interface by providing the above username and password.
● By Default our application specific created tables are not visible inside the admin
interface
● We have to register the model inside the admin interface then only it will be visible.
● We have to do the registration inside the [Link] file of the application folder.
class StudentAdmin([Link]):
list_display = ['roll', 'name', 'age', 'email',
[Link](Student, StudentAdmin)
● Now we can see the Student table related information inside the admin interface and
from there we can perform the insert and delete operations also.
Note: for every model class we have can define a separate Admin class inside the [Link] file.
In that admin class we need to specify which column should be required to display as a
list_display
Example:
class StudentAdmin([Link]):
[Link](Student, StudentAdmin)
For the editable field :
● Django ORM (Object-Relational Mapping) allows interacting with the database using
Python code instead of SQL queries. Below are various ORM methods to perform
database operations:
Note: get() raises an error if multiple records exist. Use filter() for multiple
records.
2. Filtering Data:
students = [Link](marks__lt=500)
students = [Link](marks__lte=500)
students = [Link](name__startswith="A")
students = [Link](name__icontains="kumar")
students = [Link](marks__lt=500)
[Link] += 10
[Link]()
# [Link].bulk_update(students, ["marks"])
student = [Link](id=1)
[Link]()
[Link](marks__lt=300).delete()
[Link]().delete()
students = [Link]()[:5]
students = [
[Link].bulk_create(students)
Note: To test the above ORM methods we can use the Django shell:
● Now, you can run ORM queries and test them live.
students = [Link]()
OR
● quit()
Generate the fake data using django-seed library:
● django-seed is a django based customized application to generate fake data for every
model automatically.
Documentation: [Link]
Assignment:
● Seed the 10 student records inside the table and display those records inside the
template (Bootstrap table)
● Make use of the following url:
○ students/getallstudents
Folder structure:
StudentProject/
│-- StudentProject/
│ |-- templates/
│ │-- students_list.html
cd DBProject2
[Link]:
class Student([Link]):
roll = [Link](unique=True)
name = [Link](max_length=20)
email = [Link](unique=True)
marks = [Link]()
def __str__(self):
class Course([Link]):
course_id = [Link](primary_key=True)
fee = [Link]()
duration = [Link](max_length=20)
image = [Link]()
def __str__(self):
● Do the migrations
python [Link] makemigrations
[Link]:
class StudentAdmin([Link]):
list_filter = ['address']
class CourseAdmin([Link]):
[Link](Student, StudentAdmin)
[Link](Course, CourseAdmin)
[Link]
● Add few records in both the tables(Student and Course) from the admin interface
[Link]:
def all_student_view(request):
students = [Link]()
student = [Link](roll=roll)
result = "Pass"
result = "Fail"
student = [Link](roll=roll)
[Link]()
return redirect('allstudents')
def all_course_view(request):
courses = [Link]()
course = [Link](course_id=course_id)
[Link]()
return redirect('allcourses')
● Define the mappings for the above view functions inside StudentApp/[Link] file
[Link]:
urlpatterns = [
path('getstudent/<int:roll>/', views.get_student_view,
name='getstudent'),
path('students/<int:roll>/delete/',
views.delete_student_view, name='deletestudent'),
views.delete_course_view, name='deletecourse')
● Include the above [Link] file inside the Project level [Link] file:
DBProject/[Link]
urlpatterns = [
path('admin/', [Link]),
path('', include('[Link]'))
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link
href="[Link]
[Link]" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0J
MhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<div class="container">
{% if student_list %}
<thead>
<tr>
<th>Roll</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
<th>Marks</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for student in student_list %}
<tr>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
{% endif %}
</div>
</body>
</html>
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body bgcolor="wheat">
<hr>
</body>
</html>
[Link]:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link
href="[Link]
css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6h
W+ALEwIH" crossorigin="anonymous">
<style>
body {
background-position: center;
}
</style>
</head>
<body>
<hr>
{% if course_list %}
<div class="card-body">
<h5 class="card-title">{{course.course_name}}</h5>
<p class="card-text">{{[Link]}}</p>
</div>
</div>
{% endfor %}
</div>
{% else %}
{% endif %}
</body>
</html>
[Link]
import os
MEDIA_URL = '/media/'
● With this all the uploaded images will be stored inside the media folder
Step2: Change the Course model class inside the [Link] file
class Course([Link]):
course_id = [Link](primary_key=True)
fee = [Link]()
duration = [Link](max_length=20)
image = [Link](
def __str__(self):
/media/course_images/
/media/course_images/[Link]
● Instead of storing the actual image, Django saves only the relative file path inside the
database.
urlpatterns = [
path('admin/', [Link]),
path('', include('[Link]'))
if [Link]:
urlpatterns +=
static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
● These lines enable Django to serve uploaded media files (like images, PDFs, videos,
etc.) during development when DEBUG = True.
● Django does not automatically serve media files (uploaded by users) like it does for
static files (STATIC_URL).
● So, we need this configuration to make uploaded files accessible when running the
Django development server (python [Link] runserver).
● When DEBUG = False (in production), Django does NOT serve media files. Instead,
you need a web server like NGINX or Apache to serve them.
Step 4: Display the image inside the HTML template:
Note: while migration if error comes then install the Pillow library
1. One-to-One Mapping
● Definition: A one-to-one relationship means that one record in a table is associated
with exactly one record in another table, and vice versa.
● Use Case: Used when you want to split a model into two parts for logical separation or
to store additional, optional data.
● Django Field: OneToOneField
● Database Representation: Implemented as a foreign key with a UNIQUE constraint in
the database (e.g., student_id in the StudentProfile table).
cd RelationshipProject
● A Student model might have basic details, while a StudentProfile model contains
extended information like a bio or experience.
class Student([Link]):
roll = [Link](primary_key=True)
name = [Link](max_length=100)
email = [Link](unique=True)
def __str__(self):
return [Link]
class StudentProfile([Link]):
experience = [Link](max_length=100)
student = [Link](Student,
on_delete=[Link])
def __str__(self):
Explanation:
Applying Migrations
StudentApp_student table:
StudentApp_studentprofile table:
class StudentAdmin([Link]):
class StudentProfileAdmin([Link]):
[Link](Student, StudentAdmin)
[Link](StudentProfile, StudentProfileAdmin)
● Add a few records inside both models from the admin interface.
# Create a student
student = [Link](roll=101)
profile = [Link]
Reverse Access: Django automatically creates a reverse relation (studentprofile) from Student
to StudentProfile.
profile = [Link]
print(profile)
Assignment: Update the StudentProfile experience with 4 years for all the students whose
name is Alice:
Solution: Since name isn’t a primary key, [Link](name="Alice") returns a
QuerySet of all matching records. To update all StudentProfile instances for these students,
use a loop or a bulk update.
alice_students = [Link](name="Alice")
profile = [Link]
[Link]()
updated_count =
[Link](student__name="Alice").update(experien
ce="4 years")
● Define a view function to render all the students record inside a HTML table:
StudentApp/[Link]
def get_all_student_view(request):
students = [Link]()
student = [Link](roll=roll).first()
# profile = [Link]
StudentApp/[Link]
urlpatterns = [
● Include the above [Link] file inside the Project level [Link]
urlpatterns = [
path('admin/', [Link]),
path('', include('[Link]'))
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body bgcolor="wheat">
<thead>
<tr>
<th>Roll</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body bgcolor="cyan">
<h1>Welcome {{[Link]}}</h1>
<hr>
</body>
</html>
[Link]
Definition
● A one-to-many relationship means one record in a table (the "one" side) can be
associated with multiple records in another table (the "many" side), but each record on
the "many" side is linked to only one record on the "one" side.
Use Case
Django Field
● ForeignKey: Establishes the one-to-many relationship from the "many" side (e.g.,
Employee) to the "one" side (e.g., Department).
Database Representation
● Implemented using a foreign key column in the "many" side table (e.g., department_id
in the Employee table), referencing the primary key of the "one" side table. No
uniqueness constraint is needed, as multiple records can share the same foreign key
value.
Add the following classes inside the [Link] file inside EmployeeApp folder
# EmployeeApp/[Link]
class Department([Link]):
dept_id = [Link](primary_key=True)
name = [Link](max_length=100)
location = [Link](max_length=100)
def __str__(self):
return [Link]
class Employee([Link]):
emp_id = [Link](primary_key=True)
name = [Link](max_length=100)
department = [Link](Department,
on_delete=[Link])
def __str__(self):
return [Link]
Explanation
Applying Migrations
EmployeApp_department table:
100 IT Mumbai
101 HR Chennai
EmployeeApp_employee table:
Admin Registration
# EmployeeApp/[Link]
class DepartmentAdmin([Link]):
list_display = ["dept_id", "name", "location"]
class EmployeeAdmin([Link]):
[Link](Department, DepartmentAdmin)
[Link](Employee, EmployeeAdmin)
● Add few records in both the models from the admin interface
Shell Usage:
# Create a department
Example:
Sample Operations
it_employees = [Link](department__name="IT")
it_employees = [Link](department__dept_id=100)
[Link]()
# Verify
dept1 = [Link](dept_id=100)
dept2 = [Link](dept_id=100)
print([Link](department__dept_id=100).exists()) # False
● Define the following view functions inside the [Link] file
[Link]
def get_all_dept_view(request):
depts = [Link]()
dept = [Link](dept_id=deptid).first()
emps = dept.employee_set.all()
emp = [Link](emp_id=empid).first()
dept = [Link]
● Define the url path for the above view functions inside EmployeeApp/[Link] file
EmployeeApp/[Link]
from [Link] import path
urlpatterns = [
path('<int:deptid>/employees/', views.get_dept_emps_view,
name='dept_emps'),
path('employee/<int:empid>/', views.get_emp_dept_view,
name='emp_dept')
● Include the above [Link] file inside the project level [Link] file
urlpatterns = [
path('admin/', [Link]),
path('', include('[Link]')),
path('departments/', include('[Link]'))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body bgcolor="pink">
<hr>
<thead>
<tr>
<th>Department Id</th>
<th>Department Name</th>
<th>Location</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for dept in depts %}
<tr>
<td>{{dept.dept_id}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body bgcolor="pink">
<hr>
{% if employees %}
<thead>
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Salary</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{emp.emp_id}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
{% endif %}
</body>
</html>
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body bgcolor="wheat">
</body>
</html>
[Link]
● To access the above path of EmployeeApp from the StudentApp home page i.e. from
the [Link] file, add the following link inside the [Link] file:
Definition
● A many-to-many relationship allows multiple records in one table to be associated with
multiple records in another table, and vice versa. For example, a student can enroll in
multiple courses, and a course can have multiple students enrolled.
Use Case
● Ideal for scenarios where entities have a mutual, non-exclusive relationship, such as
students enrolling in multiple courses and courses being taken by multiple students.
Django Field
Database Representation
● Implemented using an intermediary (junction) table that contains foreign keys to both
related tables. Django automatically generates this table when using ManyToManyField
● Student: Represents a student with roll number, name, email, and address.
● Course: Represents a course with course ID, name, fee, and duration.
● Relationship: A student can enroll in multiple courses, and a course can have multiple
students.
class Course([Link]):
course_id = [Link](primary_key=True)
cname = [Link](max_length=100)
duration = [Link](max_length=10)
def __str__(self):
return [Link]
class Student([Link]):
roll = [Link](primary_key=True)
name = [Link](max_length=100)
email = [Link](unique=True)
address = [Link]()
# courses = [Link](‘Course’)
def __str__(self):
return [Link]
Explanation:
● courses = [Link](Course): Defines the many-to-many relationship
directly in Student. Django creates an implicit junction table(3rd table).
● A ManyToManyField does not use ForeignKey, so on_delete is not required or
allowed.
● If a Course is deleted, Django will automatically remove the corresponding entries in
the join table.
● If a Student is deleted, their course enrollments are also removed from the join table.
● This behavior is managed by Django without needing on_delete.
Applying Migrations
Table Structure
1. Courseapp_student:
○ roll (INTEGER, PRIMARY KEY)
○ name (VARCHAR(100), NOT NULL)
○ email (VARCHAR(255), NOT NULL, UNIQUE)
○ address (TEXT, NOT NULL)
2. Courseapp_course:
○ course_id (INTEGER, PRIMARY KEY)
○ cname (VARCHAR(100), NOT NULL)
○ fee (DECIMAL(10,2), NOT NULL)
○ duration (INTEGER, NOT NULL)
3. Courseapp_student_courses (Junction Table):
○ id (INTEGER, PRIMARY KEY, AUTOINCREMENT)
○ student_id (INTEGER, FOREIGN KEY to studentapp_student.roll, NOT NULL)
○ course_id (INTEGER, FOREIGN KEY to studentapp_course.course_id, NOT NULL)
○ Constraints: Composite unique index on (student_id, course_id)
Admin Registration
● Register both the model classes inside the [Link] file of CourseApp
# CourseApp/[Link]
class StudentAdmin([Link]):
class CourseAdmin([Link]):
[Link](Student, StudentAdmin)
[Link](Course, CourseAdmin)
Note:
● Inside the above StudentAdmin class in list_display we should not use courses
directly,
● The list_display attribute expects fields that can be rendered as single values (e.g.,
strings, integers). A ManyToManyField like courses is a relationship field that points to
multiple Course objects, so Django cannot automatically display it in the admin list
view.
● When you try to include "courses" in list_display, Django raises an error because it
doesn’t know how to serialize or display the related objects in a list.
● To list all the enrolled courses we need to define list_display inside the StudentAdmin
class as follows:
class StudentAdmin([Link]):
course_names = []
course_names.append([Link])
● Add a few Courses and Students details from the admin interface.
Shell Usage:
# Create students
s2 = [Link](roll=102, name="Simran",
email="simran@[Link]", address="Mumbai")
# Create courses
Sample Operations:
python_students = [Link](courses__course_id=1)
print(python_students) # <QuerySet [<Student: Raj>, <Student:
Simran>]>
raj_courses = [Link](roll=101).[Link]()