Raw SQL queries in Django views
Last Updated :
24 Apr, 2025
Let's create a simple Django project that demonstrates the use of raw SQL queries in a view. In this example, we'll create a project to manage a list of books stored in a database. We'll create a view that retrieves books from the database using a raw SQL query and displays them on a webpage.
Setting up the project
We assume that Django is already installed in your system, If not follow the link
Starting the Project Folder
To start the project use this command:
django-admin startproject resumeuploader
cd resumeuploader
To start the app use this command
python manage.py startapp myapp
Now add this app to the 'settings.py'

Setting up the Files
model.py: Here we have created a simple Book table where we have 3 fields title, author and publication.
Python3
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_year = models.PositiveIntegerField()
def __str__(self):
return self.title
admin.py: Register your model here.
Python3
from django.contrib import admin
from .models import Book
# Register your models here.
admin.site.register(Book)
views.py: Here we wil try to understand the two ways to execute SQL quries -
- Executing custom SQL directly
- Use of Manager.raw() to fetch Data in Django
Executing custom SQL directly
The custom_query_view function defines a raw SQL query, executes it using Django's database connection, processes the results, constructs an HTML table, and returns that table as an HTTP response. This allows you to display the queried data on a webpage when the view is accessed through a URL.
Python3
from django.http import HttpResponse
from django.shortcuts import render
from django.db import connection
def custom_query_view(request):
# books is app name and book is model
query = "SELECT * FROM books_book;"
with connection.cursor() as cursor:
cursor.execute(query)
results = cursor.fetchall()
table_html = "<table><tr><th>Title</th><th>Author</th><th>Publication Year</th></tr>"
for row in results:
table_html += f"<tr><td>{row[1]}</td><td>{row[2]}</td><td>{row[3]}</td></tr>"
table_html += "</table>"
# Pass the table_html to the template
return render(request, 'index.html', {'table_html': table_html})
def home(request):
return HttpResponse('Hello, World!')