In Chapter 3, we covered the fundamentals of building dynamic Web sites with Django: setting up views and URLconfs. As we explained, a view is responsible for doing some arbitrary logic, then returning a response. In the example, our arbitrary logic was to calculate the current date and time.
In modern Web applications, the arbitrary logic often involves interacting with a database. Behind the scenes, a database-driven Web site connects to a database server, retrieves some data out of it and displays that data, nicely formatted, on a Web page. Or, similarly, the site could provide functionality that lets site visitors populate the database on their own.
Many complex Web sites provide some combination of the two. Amazon.com, for instance, is a great example of a database-driven site. Each product page is essentially an extract of Amazon’s product database formatted as HTML, and when you post a customer review, it gets inserted into the database of reviews.
Django is very well-suited for making database-driven Web sites, as it comes with easy yet powerful ways of performing database queries using Python. This chapter explains that functionality — Django’s database layer.
(Note: While it’s not strictly necessary to know basic database theory and SQL in order to use Django’s database layer, it’s highly recommended. An introduction to those concepts is out of the scope of this book, but keep reading even if you’re a database newbie. You’ll probably be able to follow along and grasp concepts based on context.)
Just as the previous chapter detailed a “dumb” way to output HTML within a view (by hard-coding HTML 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 (available at http://sourceforge.net/projects/mysql-python) 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_to_response
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_to_response('book_list.html', {'names': names})
This approach works, but some problems should jump out at you immediately:
As you might expect, Django’s database layer aims to solve these problems. Here’s a sneak preview of how the above view can be rewritten using Django’s database API:
from django.shortcuts import render_to_response
from mysite.books.models import Book
def book_list(request):
books = Book.objects.order_by('name')
return render_to_response('book_list.html', {'books': books})
We’ll explain this code a little later in this chapter. For now, just get a feel for how it looks.
Before we delve into any more code, let’s take a moment to consider the overall design of a database-driven Django Web application.
As we’ve mentioned in previous chapters, Django is designed to encourage loose coupling and strict separation between pieces of an application. If you follow this philosophy, it’s easy to make changes to one particular piece of the application without affecting other pieces of the application. In view functions, for instance, we discussed the importance of separating the business logic from the presentation logic by using a template system. With the database layer, we’re applying that same philosophy to data-access logic.
Those three pieces together — data-access logic, business logic and presentation logic — comprise a concept that’s sometimes called the “Model View Controller” (MVC) pattern of software architecture. In this pattern, “Model” refers to the data-access layer, “View” refers to the part of the system that selects what to display and how to display it, and “Controller” refers to the part of the system that decides which view to use, depending on user input, accessing the model as needed.
Why the acronym?
MVC? MTV? What’s the point of these terms?
The goal of explicitly defining patterns such as MVC is mostly to streamline communication among developers. Instead of having to tell your coworkers, “Let’s make an abstraction of the data-access, then have a separate layer that handles data display, and let’s put a layer in the middle that regulates this,” you can take advantage of a shared vocabulary and say, “Let’s use the MVC pattern here.”
Django follows this MVC pattern closely enough that it can be called an MVC framework. Here’s roughly how the M, V and C break down in Django:
Because the “C” is handled by the framework itself and most of the excitement in Django happens in models, templates and views, Django has been referred to as an MTV framework. In the MTV development pattern,
If you’re familiar with other MVC Web-development frameworks, such as Ruby on Rails, you may consider Django views to be the “controllers” and Django templates to be the “views.” This is an unfortunate confusion brought about by differing interpretations of MVC. In Django’s interpretation of MVC, the “view” describes the data that gets presented to the user; it’s not necessarily just how the data looks, but which data is presented. In contrast, Ruby on Rails and similar frameworks suggest that the controller’s job includes deciding which data gets presented to the user, whereas the view is strictly how the data looks, not which data is presented.
Neither interpretation is more “correct” than the other. The important thing is to understand the underlying concepts.
With all of that philosophy in mind, let’s start exploring Django’s database layer. First, we need to take care of some initial configuration; we need to tell Django which database server to use and how to connect to it.
We’ll assume you’ve set up a database server, activated it and created a database within it (e.g., using a CREATE DATABASE statement). SQLite is a special case; in that case, there’s no database to create, because SQLite uses standalone files on the filesystem to store its data.
As TEMPLATE_DIRS in the previous chapter, database configuration lives in the Django settings file, called settings.py by default. Edit that file and look for the database settings:
DATABASE_ENGINE = '' DATABASE_NAME = '' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = ''
Here’s a rundown of each setting.
DATABASE_ENGINE tells Django which database engine to use. If you’re using a database with Django, DATABASE_ENGINE must be set to one of the following strings:
Setting |
Database |
Required adapter |
|---|---|---|
postgresql |
PostgreSQL |
psycopg version 1.x, http://initd.org/projects/psycopg1 |
postgresql_psycopg2 |
PostgreSQL |
psycopg version 2.x, http://initd.org/projects/psycopg2 |
mysql |
MySQL |
|
sqlite3 |
SQLite |
No adapter needed if using Python 2.5+. Otherwise, pysqlite, http://initd.org/tracker/pysqlite |
ado_mssql |
Microsoft SQL Server |
adodbapi version 2.0.1+, http://adodbapi.sourceforge.net/ |
oracle |
Oracle |
Note that for whichever database backend you use, you’ll need to download and install the appropriate database adapter. Each one is available for free on the Web.
DATABASE_NAME tells Django what the name of your database is. If you’re using SQLite, specify the full filesystem path to the database file on your filesystem, e.g., '/home/django/mydata.db'
DATABASE_USER tells Django which username to use when connecting to your database. If you’re using SQLite, leave this blank.
DATABASE_PASSWORD tells Django which password to use when connecting to your database. If you’re using SQLite or have an empty password, leave this blank.
DATABASE_HOST tells Django which host to use when connecting to your database. If your database is on the same computer as your Django installation (i.e., localhost), leave this blank. If you’re using SQLite, leave this blank.
MySQL is a special case here. If this value starts with a forward slash ('/') and you’re using MySQL, MySQL will connect via a Unix socket to the specified socket. For example:
DATABASE_HOST = '/var/run/mysql'
If you’re using MySQL and this value doesn’t start with a forward slash, then this value is assumed to be the host.
DATABASE_PORT tells Django which port to use when connecting to your database. If you’re using SQLite, leave this blank. Otherwise, if you leave this blank, the underlying database adapter will use whichever port is default for your given database server. In most cases, the default port is fine, so you can leave this blank.
Once you’ve entered those settings, test your configuration. First, from within the mysite project directory you created in Chapter 2, run the command python manage.py shell.
You’ll notice this starts a Python interactive interpreter. Looks can be deceiving, though! There’s an important difference between running the command python manage.py shell within your Django project directory and the more generic python. The latter is the basic Python shell, but the former tells Django which settings file to use before it starts the shell. This is a key requirement for doing database queries: Django needs to know which settings file to use in order to get your database connection information.
Behind the scenes, python manage.py shell sets the environment variable DJANGO_SETTINGS_MODULE. We’ll cover the subtleties of this later, but for now, just know that you should use python manage.py shell whenever you need to drop into the Python interpreter to do Django-specific tinkering.
Once you’ve entered the shell, type these commands to test your database configuration:
>>> from django.db import connection >>> cursor = connection.cursor()
If nothing happens, then your database is configured properly. Otherwise, check the error message for clues about what’s wrong. Here are some common errors:
| Error message | Solution |
|---|---|
| You haven’t set the DATABASE_ENGINE setting yet. | Set the DATABASE_ENGINE setting to something other than an empty string. |
| Environment variable DJANGO_SETTINGS_MODULE is undefined. | Run the command python manage.py shell rather than python. |
| Error loading _____ module: No module named _____. | You haven’t installed the appropriate database-specific adapter (e.g. psycopg or MySQLdb). |
| _____ isn’t an available database backend. | Set your DATABASE_ENGINE setting to one of the valid engine settings described above. Perhaps you made a typo? |
| database _____ does not exist | Change the DATABASE_NAME setting to point to a database that exists, or execute the appropriate CREATE DATABASE statement in order to create it. |
| role _____ does not exist | Change DATABASE_USER setting to point to a user that exists, or create the user in your database. |
| could not connect to server | Make sure DATABASE_HOST and DATABASE_PORT are set correctly, and make sure the server is running. |
Now that you’ve verified the connection is working, it’s time to create a Django app — a bundle of Django code, including models and views, that lives together in a single Python package and represents a full Django application.
It’s worth explaining the terminology here, because this tends to trip up beginners. We’d already created a project, in Chapter 2, so what’s the difference between a project and an app? The difference is that of configuration vs. code:
A project is an instance of a certain set of Django apps, plus the configuration for those apps.
Technically, the only requirement of a project is that it supplies a settings file, which defines the database connection information, the list of installed apps, the TEMPLATE_DIRS, etc.
An app is a portable set of Django functionality, usually including models and views, that lives together in a single Python package.
For example, Django comes with a number of apps, such as a commenting system and an automatic admin interface. A key thing to note about these apps is that they’re portable and reusable across multiple projects.
There are very few hard-and-fast rules about how you fit your Django code into this scheme; it’s flexible. If you’re building a simple Web site, you may only use a single app. If you’re building a complex Web site with several rather unrelated pieces such as an e-commerce system and a message board, you’ll probably want to split those into separate apps so that you’ll be able to reuse them individually in the future.
Indeed, you don’t necessarily need to create apps at all, as evidenced by the example view functions we’ve created so far in this book. In those cases, we simply created a file called views.py, filled it with view functions and pointed our URLconf at those functions. No “apps” were needed.
However, there’s one requirement regarding the app convention: If you’re using Django’s database layer (models), you must create a Django app. Models must live within apps. Thus, in order to start writing our models, we’ll need to create a new app.
Within the mysite project directory you created in Chapter 2, type this command to create a new app:
python manage.py startapp books
(Why books? That’s the sample book app we’ll be building together.)
This command does not result in any output, but it will have created a books directory within the mysite directory. Let’s look at the contents of that directory:
books/
__init__.py
models.py
views.py
These files will contain your models and views for this app.
Have a look at models.py and views.py in your favorite text editor. Both files are empty, except for an import in models.py. This is the blank slate for your Django app.
As we discussed above, the “M” in “MTV” stands for “Model.” A Django model is a description of the data in your database, represented as Python code. It’s your data layout — the equivalent of your SQL CREATE TABLE statements — except it’s in Python instead of SQL, and it includes more than just database definitions. Django uses a model to execute SQL code behind the scenes and return convenient Python data structures representing the rows in your database tables. Django also uses models to represent higher-level concepts that SQL can’t necessarily handle.
If you’re familiar with databases, your immediate thought might be, “Isn’t it redundant to define data models in Python and in SQL?” Django works the way it does for several reasons:
Introspection requires overhead and is imperfect.
In order to provide convenient data-access APIs, Django needs to know the database layout somehow, and there are two ways of accomplishing this. The first way would be to explicitly describe the data in Python, and the second way would be to introspect the database at runtime to determine the data models.
This second way seems cleaner, because the metadata about your tables only lives in one place, but it introduces a few problems. First, introspecting a database at runtime obviously requires overhead. If the framework had to introspect the database each time it processed a request, or even when the Web server was initialized, this would incur an unacceptable level of overhead. (While some believe that level of overhead is acceptable, Django’s developers aim to trim as much framework overhead as possible, and this approach has succeeded in making Django faster than its high-level framework competitors in benchmarks.) Second, some databases, notably older versions of MySQL, do not store sufficient metadata for accurate and complete introspection.
Writing Python is fun, and keeping everything in Python limits the number of times your brain has to do a “context switch.” It helps productivity if you keep yourself in a single programming environment/mentality for as long as possible. Having to write SQL, then Python, then SQL again, is disruptive.
Having data models stored as code rather than in your database makes it easier to keep your models under version control. This way, you can easily keep track of changes to your data layouts.
SQL only allows for a certain level of metadata about a data layout. Most database systems, for example, do not provide a specialized data type for representing e-mail addresses or URLs. Django models do. The advantage of higher-level data types is higher productivity and more reusable code.
SQL is inconsistent across database platforms. If you’re distributing a Web application, for example, it’s much more pragmatic to distribute a Python module that describes your data layout than separate sets of CREATE TABLE statements for MySQL, PostgreSQL and SQLite.
A drawback of this approach, however, is that it’s possible for the Python code to get out of sync with what’s actually in the database. If you make changes to a Django model, you’ll need to make the same changes inside your database to keep your database consistent with the model. We’ll detail some strategies for handling this problem later in this chapter.
Finally, we should note that Django includes a utility that can generate models by introspecting an existing database. This is useful for quickly getting up and running with legacy data.
As an ongoing example in this chapter and the next chapter, we’ll focus on a basic book/author/publisher data layout. We use this as our example because the conceptual relationships between books, authors and publishers are well-known, and this is a common data layout used in introductory SQL textbooks. You’re also reading a book, written by authors, produced by a publisher!
We’ll suppose the following concepts, fields and relationships:
The first step in using this database layout with Django is to express it as Python code. In the models.py file that was created by the startapp command, enter the following:
from django.db import models
class Publisher(models.Model):
name = models.CharField(maxlength=30)
address = models.CharField(maxlength=50)
city = models.CharField(maxlength=60)
state_province = models.CharField(maxlength=30)
country = models.CharField(maxlength=50)
website = models.URLField()
class Author(models.Model):
salutation = models.CharField(maxlength=10)
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=40)
email = models.EmailField()
headshot = models.ImageField(upload_to='/tmp')
class Book(models.Model):
title = models.CharField(maxlength=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
We will cover model syntax and options throughout this chapter, but let’s quickly examine this code to cover the basics. The first thing to notice is that each model is represented by a Python class that is a subclass of django.db.models.Model. The parent class, Model, contains all the machinery necessary to make these objects capable of interacting with a database — and that leaves our models responsible solely for defining their fields, in a nice and compact syntax. Believe it or not, this is all the code we need to write to have basic data access with Django.
Each model generally corresponds to a single database table, and each attribute on a model generally corresponds to a column in that database table. The attribute name corresponds to the column’s name, and the type of field (e.g., CharField) corresponds to the database column type (e.g., varchar). For example, the Publisher model is equivalent to the following table (assuming PostgreSQL CREATE TABLE syntax):
CREATE TABLE "books_publisher" (
"id" serial NOT NULL PRIMARY KEY,
"name" varchar(30) NOT NULL,
"address" varchar(50) NOT NULL,
"city" varchar(60) NOT NULL,
"state_province" varchar(30) NOT NULL,
"country" varchar(50) NOT NULL,
"website" varchar(200) NOT NULL
);
Indeed, Django can generate that CREATE TABLE statement itself, as we’ll see in a moment.
The exception to the one-class-per-database-table rule is the case of many-to-many relationships. In our example models, Book has a ManyToManyField called authors. This designates that a book has one or many authors, but the Book database table doesn’t get an authors column. Rather, Django creates an additional table — a many-to-many “join table” — that handles the mapping of books to authors.
Finally, note we haven’t explicitly defined a primary key in any of these models. Unless you instruct it otherwise, Django automatically gives every model an integer primary key field called id. Each Django model is required to have a single-column primary key.
We’ve written the code; now, let’s create the tables in our database. In order to do that, the first step is to activate these models in our Django project. We do that by adding this books app to the list of installed apps in the settings file.
Edit the settings.py file again, and look for the INSTALLED_APPS setting. INSTALLED_APPS tells Django which apps are activated for a given project. By default, it looks something like this:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
)
Temporarily comment out all four of those strings by putting a hash character (#) in front of them. (They’re included by default as a common-case convenience, but we’ll activate them and discuss them later.) Then, add 'mysite.books' to the INSTALLED_APPS list, so the setting ends up looking like this:
INSTALLED_APPS = (
#'django.contrib.auth',
#'django.contrib.contenttypes',
#'django.contrib.sessions',
#'django.contrib.sites',
'mysite.books',
)
(As we’re dealing with a single-element tuple here, don’t forget the trailing comma. By the way, this book’s authors prefer to put a comma after every element of a tuple, regardless of whether the tuple has only a single element. This avoids the issue of forgetting commas, and there’s no penalty for using that extra comma.)
'mysite.books' refers to the books app we’re working on. Each app in INSTALLED_APPS is represented by its full Python path — that is, the path of packages, separated by dots, leading to the app package.
Now that the Django app has been activated in the settings file, we can create the database tables in our database. First, let’s validate the models by running this command:
python manage.py validate
The validate command checks whether your models’ syntax and logic are correct. If all is well, you’ll see the message 0 errors found. If you don’t, make sure you typed in the model code correctly. The error output should give you helpful information about what was wrong with the code.
Any time you think you have problems with your models, run python manage.py validate. It tends to catch all the common model problems.
If your models are valid, run the following command for Django to generate CREATE TABLE statements for your models in the books app (with colorful syntax highlighting available if you’re using Unix):
python manage.py sqlall books
In this command, books is the name of the app. It’s what you specified when you ran the command manage.py startapp. When you run the command, you should see something like this:
BEGIN;
CREATE TABLE "books_publisher" (
"id" serial NOT NULL PRIMARY KEY,
"name" varchar(30) NOT NULL,
"address" varchar(50) NOT NULL,
"city" varchar(60) NOT NULL,
"state_province" varchar(30) NOT NULL,
"country" varchar(50) NOT NULL,
"website" varchar(200) NOT NULL
);
CREATE TABLE "books_book" (
"id" serial NOT NULL PRIMARY KEY,
"title" varchar(100) NOT NULL,
"publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id"),
"publication_date" date NOT NULL
);
CREATE TABLE "books_author" (
"id" serial NOT NULL PRIMARY KEY,
"salutation" varchar(10) NOT NULL,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(40) NOT NULL,
"email" varchar(75) NOT NULL,
"headshot" varchar(100) NOT NULL
);
CREATE TABLE "books_book_authors" (
"id" serial NOT NULL PRIMARY KEY,
"book_id" integer NOT NULL REFERENCES "books_book" ("id"),
"author_id" integer NOT NULL REFERENCES "books_author" ("id"),
UNIQUE ("book_id", "author_id")
);
CREATE INDEX books_book_publisher_id ON "books_book" ("publisher_id");
COMMIT;
Note the following:
The sqlall command doesn’t actually create the tables or otherwise touch your database — it just prints output to the screen so you can see what SQL Django would execute if you asked it. If you wanted to, you could copy and paste this SQL into your database client, or use Unix pipes to pass it directly. However, Django provides an easier way of committing the SQL to the database. Run the syncdb command, like so:
python manage.py syncdb
You’ll see something like this:
Creating table books_publisher Creating table books_book Creating table books_author Installing index for books.Book model
The syncdb command is a simple “sync” of your models to your database. It looks at all of the models in each app in your INSTALLED_APPS setting, checks the database to see whether the appropriate tables exist yet, and creates the tables if they don’t yet exist. Note that syncdb does not sync changes in models or deletions of models; if you make a change to a model or delete a model, and you want to update the database, syncdb will not handle that. (More on this later.)
If you run python manage.py syncdb again, nothing happens, because you haven’t added any models to the books app, or added any apps to INSTALLED_APPS. Ergo, it’s always safe to run python manage.py syncdb — it won’t clobber things.
If you’re interested, take a moment to dive into your database server’s command-line client and see the database tables Django created. You can manually run the command-line client — e.g., psql for PostgreSQL — or you can run the command python manage.py dbshell, which will figure out which command-line client to run, depending on your DATABASE_SERVER setting. The latter is almost always more convenient.
Once you’ve created a model, Django automatically provides a high-level Python API for working with those models. Try it out by running python manage.py shell and typing the following:
>>> from books.models import Publisher >>> p = Publisher(name='Apress', address='2560 Ninth St.', ... city='Berkeley', state_province='CA', country='U.S.A.', ... website='http://www.apress.com/') >>> p.save() >>> p = Publisher(name="O'Reilly", address='10 Fawcett St.', ... city='Cambridge', state_province='MA', country='U.S.A.', ... website='http://www.oreilly.com/') >>> p.save() >>> publisher_list = Publisher.objects.all() >>> publisher_list [<Publisher: Publisher object>, <Publisher: Publisher object>]
In only a few lines of code, this has accomplished quite a bit. The highlights:
Naturally, you can do quite a lot with the Django database API — but first, let’s take care of a small annoyance.
Above, when we printed out the list of publishers, all we got was this unhelpful display that makes it difficult to tell the Publisher objects apart:
[<Publisher: Publisher object>, <Publisher: Publisher object>]
We can fix this easily by adding a method called __str__() to our Publisher object. A __str__() method tells Python how to display the “string” representation of an object. You can see this in action by adding a __str__() method to the three models:
class Publisher(models.Model):
name = models.CharField(maxlength=30)
address = models.CharField(maxlength=50)
city = models.CharField(maxlength=60)
state_province = models.CharField(maxlength=30)
country = models.CharField(maxlength=50)
website = models.URLField()
def __str__(self):
return self.name
class Author(models.Model):
salutation = models.CharField(maxlength=10)
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=40)
email = models.EmailField()
headshot = models.ImageField(upload_to='/tmp')
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(maxlength=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __str__(self):
return self.title
As you can see, a __str__() method can do whatever it needs to do in order to return a string representation. Here, the __str__() methods for Publisher and Book simply return the object’s name and title, respectively, but the __str__() for Author is slightly more complex — it pieces together the first_name and last_name fields. The only requirement for __str__() is that it return a string. If __str__() doesn’t return a string — if it returns, say, an integer — then Python will raise a TypeError with a message like "__str__ returned non-string".
For the changes to take effect, exit out of the Python shell and enter it again with python manage.py shell. (This is the easiest way to make code changes take effect.) Now, the list of Publisher objects is much easier to understand:
>>> from books.models import Publisher >>> publisher_list = Publisher.objects.all() >>> publisher_list [<Publisher: Apress>, <Publisher: O'Reilly>]
Make sure any model you define has a __str__() method — not only for your own convenience when using the interactive interpreter, but also because Django uses the output of __str__() in several places when it needs to display objects.
Finally, note that __str__() is a good example of adding behavior to models. A Django model describes more than the database table layout for an object; it also describes any functionality that object knows how to do. __str__() is one example of such functionality — a model knows how to display itself.
This chapter is not yet finished.
Comments are closed on this chapter.
We're no longer accepting comments on this version of this chapter.
Many thanks to all those who commented.
About this comment system
This site is using a contextual comment system to help us gather targeted feedback about the book. Instead of commenting on an entire chapter, you can leave comments on any indivdual "block" in the chapter. A "block" with comments looks like this:
A "block" is a paragraph, list item, code sample, or other small chunk of content. It'll get highlighted when you select it:
To post a comment on a block, just click in the gutter next to the bit you want to comment on:
As we edit the book, we'll review everyone's comments and roll them into a future version of the book. We'll mark reviewed comments with a little checkmark:
Please make sure to leave a full name (and not a nickname or screenname) if you'd like your contributions acknowledged in print.
Many, many thanks to Jack Slocum; the inspiration and much of the code for the comment system comes from Jack's blog, and this site couldn't have been built without his wonderful
YAHOO.extlibrary. Thanks also to Yahoo for YUI itself.