Book Image

Learning Website Development with Django

Book Image

Learning Website Development with Django

Overview of this book

Table of Contents (18 chapters)
Learning Website Development with Django
Credits
About the Author
About the Reviewers
Preface
Index

Model Managers and Custom SQL


The Django model and database APIs are very powerful. We used them to construct a variety of query sets throughout the book. Most of the time, these APIs will be sufficient for your needs. There are times, however, when the task at hand requires raw SQL power. For example, you may want to use SQL aggregate functions such as sum or avg to obtain certain types of information from the database. The database layer of Django does not provide methods that offer similar functionality to aggregate functions at the time being. To overcome this, Django enables you to send raw SQL to your database for such special situations.

To send SQL queries to the database in Django, use the following code:

from django.db import connection

query = '-- SQL code goes here. --'
cursor = connection.cursor()
cursor.execute(query)

If you use a SELECT query, you can retrieve the returned rows using:

rows = cursor.fetchall()

rows is a list of rows. Each row is a list of values that map to columns...