The Django model and database APIs are very powerful. We used them to construct a variety of query sets throughout the book. Mostly, these APIs will be sufficient for your needs. However, there are times 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 of writing. 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...