Just as Chapter 2, Views and Urlconfs, detailed a "dumb" way to produce output within a view (by hard-coding the text directly within the view), there's a "dumb" way to retrieve data from a database in a view. It's simple: just use any existing Python library to execute an SQL query and do something with the results. In this example view, we use the MySQLdb
library to connect to a MySQL database, retrieve some records, and feed them to a template for display as a web page:
from django.shortcuts import render import MySQLdb def book_list(request): db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost') cursor = db.cursor() cursor.execute('SELECT name FROM books ORDER BY name') names = [row[0] for row in cursor.fetchall()] db.close() return render(request, 'book_list.html', {'names': names})
This approach works, but some problems should jump...