Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 1390 lines (1055 sloc) 59.263 kb
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1 =================
2 Chapter 5: Models
3 =================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
4
5 In Chapter 3, we covered the fundamentals of building dynamic Web sites
6 with Django: setting up views and URLconfs. As we explained, a view is
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
7 responsible for doing *some arbitrary logic*, and then returning a response. In
8 one of the examples, our arbitrary logic was to calculate the current date and
9 time.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
10
11 In modern Web applications, the arbitrary logic often involves interacting
12 with a database. Behind the scenes, a *database-driven Web site* connects to
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
13 a database server, retrieves some data out of it, and displays that data on a
14 Web page. The site might also provide ways for site visitors to populate the
15 database on their own.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
16
17 Many complex Web sites provide some combination of the two. Amazon.com, for
18 instance, is a great example of a database-driven site. Each product page is
19 essentially a query into Amazon's product database formatted as HTML, and when
20 you post a customer review, it gets inserted into the database of reviews.
21
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
22 Django is well suited for making database-driven Web sites, because it comes
23 with easy yet powerful tools for performing database queries using Python. This
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
24 chapter explains that functionality: Django's database layer.
25
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
26 (Note: While it's not strictly necessary to know basic relational database
27 theory and SQL in order to use Django's database layer, it's highly
28 recommended. An introduction to those concepts is beyond the scope of this
29 book, but keep reading even if you're a database newbie. You'll probably be
30 able to follow along and grasp concepts based on the context.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
31
32 The "Dumb" Way to Do Database Queries in Views
33 ==============================================
34
35 Just as Chapter 3 detailed a "dumb" way to produce output within a
36 view (by hard-coding the text directly within the view), there's a "dumb" way to
37 retrieve data from a database in a view. It's simple: just use any existing
38 Python library to execute an SQL query and do something with the results.
39
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
40 In this example view, we use the ``MySQLdb`` library (available via
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
41 http://www.djangoproject.com/r/python-mysql/) to connect to a MySQL database,
42 retrieve some records, and feed them to a template for display as a Web page::
43
a4724d5 @RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
44 from django.shortcuts import render
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
45 import MySQLdb
46
47 def book_list(request):
48 db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
49 cursor = db.cursor()
50 cursor.execute('SELECT name FROM books ORDER BY name')
51 names = [row[0] for row in cursor.fetchall()]
52 db.close()
a4724d5 @RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
53 return render(request, 'book_list.html', {'names': names})
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
54
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
55 .. SL Tested ok
56
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
57 This approach works, but some problems should jump out at you immediately:
58
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
59 * We're hard-coding the database connection parameters. Ideally, these
60 parameters would be stored in the Django configuration.
61
62 * We're having to write a fair bit of boilerplate code: creating a
63 connection, creating a cursor, executing a statement, and closing the
64 connection. Ideally, all we'd have to do is specify which results we
65 wanted.
66
67 * It ties us to MySQL. If, down the road, we switch from MySQL to
68 PostgreSQL, we'll have to use a different database adapter (e.g.,
69 ``psycopg`` rather than ``MySQLdb``), alter the connection parameters,
70 and -- depending on the nature of the SQL statement -- possibly rewrite
71 the SQL. Ideally, the database server we're using would be abstracted, so
72 that a database server change could be made in a single place. (This
73 feature is particularly relevant if you're building an open-source Django
74 application that you want to be used by as many people as possible.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
75
76 As you might expect, Django's database layer aims to solve these problems.
77 Here's a sneak preview of how the previous view can be rewritten using Django's
78 database API::
79
a4724d5 @RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
80 from django.shortcuts import render
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
81 from mysite.books.models import Book
82
83 def book_list(request):
84 books = Book.objects.order_by('name')
a4724d5 @RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
85 return render(request, 'book_list.html', {'books': books})
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
86
87 We'll explain this code a little later in the chapter. For now, just get a
88 feel for how it looks.
89
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
90 The MTV (or MVC) Development Pattern
91 ====================================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
92
93 Before we delve into any more code, let's take a moment to consider the overall
94 design of a database-driven Django Web application.
95
96 As we mentioned in previous chapters, Django is designed to encourage loose
97 coupling and strict separation between pieces of an application. If you follow
98 this philosophy, it's easy to make changes to one particular piece of the
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
99 application without affecting the other pieces. In view functions, for
100 instance, we discussed the importance of separating the business logic from the
101 presentation logic by using a template system. With the database layer, we're
102 applying that same philosophy to data access logic.
103
104 Those three pieces together -- data access logic, business logic, and
105 presentation logic -- comprise a concept that's sometimes called the
106 *Model-View-Controller* (MVC) pattern of software architecture. In this
107 pattern, "Model" refers to the data access layer, "View" refers to the part of
108 the system that selects what to display and how to display it, and
109 "Controller" refers to the part of the system that decides which view to use,
110 depending on user input, accessing the model as needed.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
111
112 .. admonition:: Why the Acronym?
113
114 The goal of explicitly defining patterns such as MVC is mostly to
115 streamline communication among developers. Instead of having to tell your
116 coworkers, "Let's make an abstraction of the data access, then let's have a
117 separate layer that handles data display, and let's put a layer in the
118 middle that regulates this," you can take advantage of a shared vocabulary
119 and say, "Let's use the MVC pattern here."
120
121 Django follows this MVC pattern closely enough that it can be called an MVC
122 framework. Here's roughly how the M, V, and C break down in Django:
123
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
124 * *M*, the data-access portion, is handled by Django's database layer,
125 which is described in this chapter.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
126
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
127 * *V*, the portion that selects which data to display and how to display
128 it, is handled by views and templates.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
129
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
130 * *C*, the portion that delegates to a view depending on user input, is
131 handled by the framework itself by following your URLconf and calling the
132 appropriate Python function for the given URL.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
133
134 Because the "C" is handled by the framework itself and most of the excitement
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
135 in Django happens in models, templates and views, Django has been referred to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
136 as an *MTV framework*. In the MTV development pattern,
137
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
138 * *M* stands for "Model," the data access layer. This layer contains
139 anything and everything about the data: how to access it, how to validate
140 it, which behaviors it has, and the relationships between the data.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
141
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
142 * *T* stands for "Template," the presentation layer. This layer contains
143 presentation-related decisions: how something should be displayed on a
144 Web page or other type of document.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
145
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
146 * *V* stands for "View," the business logic layer. This layer contains the
147 logic that access the model and defers to the appropriate template(s).
148 You can think of it as the bridge between models and templates.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
149
150 If you're familiar with other MVC Web-development frameworks, such as Ruby on
151 Rails, you may consider Django views to be the "controllers" and Django
152 templates to be the "views." This is an unfortunate confusion brought about by
153 differing interpretations of MVC. In Django's interpretation of MVC, the "view"
154 describes the data that gets presented to the user; it's not necessarily just
155 *how* the data looks, but *which* data is presented. In contrast, Ruby on Rails
156 and similar frameworks suggest that the controller's job includes deciding
157 which data gets presented to the user, whereas the view is strictly *how* the
158 data looks, not *which* data is presented.
159
160 Neither interpretation is more "correct" than the other. The important thing is
161 to understand the underlying concepts.
162
163 Configuring the Database
164 ========================
165
166 With all of that philosophy in mind, let's start exploring Django's database
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
167 layer. First, we need to take care of some initial configuration; we need to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
168 tell Django which database server to use and how to connect to it.
169
170 We'll assume you've set up a database server, activated it, and created a
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
171 database within it (e.g., using a ``CREATE DATABASE`` statement). If you're
172 using SQLite, no such setup is required, because SQLite uses standalone files
173 on the filesystem to store its data.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
174
175 As with ``TEMPLATE_DIRS`` in the previous chapter, database configuration lives in
176 the Django settings file, called ``settings.py`` by default. Edit that file and
177 look for the database settings::
178
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
179 DATABASES = {
180 'default': {
6651b56 @Funkmyster Ch5 - fixes for DB configs
Funkmyster authored
181 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
182 'NAME': '', # Or path to database file if using sqlite3.
183 'USER': '', # Not used with sqlite3.
184 'PASSWORD': '', # Not used with sqlite3.
185 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
186 'PORT': '', # Set to empty string for default. Not used with sqlite3.
187 }
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
188 }
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
189
190 Here's a rundown of each setting.
191
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
192 * ``ENGINE`` tells Django which database engine to use. If you're
193 using a database with Django, ``ENGINE`` must be set to one of
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
194 the strings shown in Table 5-1.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
195
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
196 .. table:: Table 5-1. Database Engine Settings
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
197
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
198 ============================================ ============ ================================================
199 Setting Database Required Adapter
200 ============================================ ============ ================================================
201 ``django.db.backends.postgresql_psycopg2`` PostgreSQL ``psycopg`` version 2.x,
202 http://www.djangoproject.com/r/python-pgsql/.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
203
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
204 ``django.db.backends.mysql`` MySQL ``MySQLdb``,
205 http://www.djangoproject.com/r/python-mysql/.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
206
6651b56 @Funkmyster Ch5 - fixes for DB configs
Funkmyster authored
207 ``django.db.backends.sqlite3`` SQLite No adapter needed.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
208
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
209 ``django.db.backends.oracle`` Oracle ``cx_Oracle``,
210 http://www.djangoproject.com/r/python-oracle/.
211 ============================================ ============ ================================================
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
212
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
213 Note that for whichever database back-end you use, you'll need to download
214 and install the appropriate database adapter. Each one is available for
215 free on the Web; just follow the links in the "Required Adapter" column
216 in Table 5-1. If you're on Linux, your distribution's package-management
217 system might offer convenient packages. (Look for packages called
218 ``python-postgresql`` or ``python-psycopg``, for example.)
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
219
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
220 Example::
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
221
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
222 'ENGINE': 'django.db.backends.postgresql_psycopg2',
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
223
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
224 * ``NAME`` tells Django the name of your database. For example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
225
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
226 'NAME': 'mydb',
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
227
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
228 If you're using SQLite, specify the full filesystem path to the database
229 file on your filesystem. For example::
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
230
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
231 'NAME': '/home/django/mydata.db',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
232
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
233 As for where you put that SQLite database, we're using the ``/home/django``
234 directory in this example, but you should pick a directory that works
235 best for you.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
236
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
237 * ``USER`` tells Django which username to use when connecting to
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
238 your database. For example: If you're using SQLite, leave this blank.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
239
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
240 * ``PASSWORD`` tells Django which password to use when connecting
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
241 to your database. If you're using SQLite or have an empty password, leave
242 this blank.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
243
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
244 * ``HOST`` tells Django which host to use when connecting to your
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
245 database. If your database is on the same computer as your Django
246 installation (i.e., localhost), leave this blank. If you're using SQLite,
247 leave this blank.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
248
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
249 MySQL is a special case here. If this value starts with a forward slash
250 (``'/'``) and you're using MySQL, MySQL will connect via a Unix socket to
251 the specified socket, for example::
252
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
253 'HOST': '/var/run/mysql',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
254
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
255 .. SL The usual convention is for the socket to be named 'mysql.sock' or similar,
256 .. SL so would '/var/run/mysql.sock' be a better example?
257
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
258 If you're using MySQL and this value *doesn't* start with a forward
259 slash, then this value is assumed to be the host.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
260
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
261 * ``PORT`` tells Django which port to use when connecting to your
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
262 database. If you're using SQLite, leave this blank. Otherwise, if you
263 leave this blank, the underlying database adapter will use whichever
264 port is default for your given database server. In most cases, the
265 default port is fine, so you can leave this blank.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
266
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
267 Once you've entered those settings and saved ``settings.py``, it's a good idea
268 to test your configuration. To do this, run ``python manage.py shell`` as in
269 the last chapter, from within the ``mysite`` project directory. (As we pointed
270 out last chapter ``manage.py shell`` is a way to run the Python interpreter
271 with the correct Django settings activated. This is necessary in our case,
272 because Django needs to know which settings file to use in order to get your
273 database connection information.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
274
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
275 In the shell, type these commands to test your database configuration::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
276
277 >>> from django.db import connection
278 >>> cursor = connection.cursor()
279
280 If nothing happens, then your database is configured properly. Otherwise, check
281 the error message for clues about what's wrong. Table 5-2 shows some common errors.
282
283 .. table:: Table 5-2. Database Configuration Error Messages
284
285 ========================================================= ===============================================
286 Error Message Solution
287 ========================================================= ===============================================
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
288 You haven't set the ENGINE setting yet. Set the ``ENGINE`` setting to
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
289 something other than an empty string. Valid
290 values are in Table 5-1.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
291 Environment variable DJANGO_SETTINGS_MODULE is undefined. Run the command ``python manage.py shell``
292 rather than ``python``.
293 Error loading _____ module: No module named _____. You haven't installed the appropriate
294 database-specific adapter (e.g., ``psycopg``
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
295 or ``MySQLdb``). Adapters are *not* bundled
296 with Django, so it's your responsibility to
297 download and install them on your own.
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
298 _____ isn't an available database backend. Set your ``ENGINE`` setting to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
299 one of the valid engine settings described
300 previously. Perhaps you made a typo?
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
301 database _____ does not exist Change the ``NAME`` setting to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
302 point to a database that exists, or
303 execute the appropriate
304 ``CREATE DATABASE`` statement in order to
305 create it.
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
306 role _____ does not exist Change the ``USER`` setting to point
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
307 to a user that exists, or create the user
308 in your database.
e9e1487 @Funkmyster Ch5 - Update DB configs to version 1.4
Funkmyster authored
309 could not connect to server Make sure ``HOST`` and
310 ``PORT`` are set correctly, and
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
311 make sure the database server is running.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
312 ========================================================= ===============================================
313
314 Your First App
315 ==============
316
317 Now that you've verified the connection is working, it's time to create a
318 *Django app* -- a bundle of Django code, including models and views, that
319 lives together in a single Python package and represents a full Django
320 application.
321
322 It's worth explaining the terminology here, because this tends to trip up
323 beginners. We'd already created a *project*, in Chapter 2, so what's the
324 difference between a *project* and an *app*? The difference is that of
325 configuration vs. code:
326
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
327 * A project is an instance of a certain set of Django apps, plus the
328 configuration for those apps.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
329
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
330 Technically, the only requirement of a project is that it supplies a
331 settings file, which defines the database connection information, the
332 list of installed apps, the ``TEMPLATE_DIRS``, and so forth.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
333
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
334 * An app is a portable set of Django functionality, usually including
335 models and views, that lives together in a single Python package.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
336
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
337 For example, Django comes with a number of apps, such as a commenting
338 system and an automatic admin interface. A key thing to note about these
339 apps is that they're portable and reusable across multiple projects.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
340
341 There are very few hard-and-fast rules about how you fit your Django code into
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
342 this scheme. If you're building a simple Web site, you may use only a single
343 app. If you're building a complex Web site with several unrelated pieces such
344 as an e-commerce system and a message board, you'll probably want to split
345 those into separate apps so that you'll be able to reuse them individually in
346 the future.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
347
348 Indeed, you don't necessarily need to create apps at all, as evidenced by the
349 example view functions we've created so far in this book. In those cases, we
350 simply created a file called ``views.py``, filled it with view functions, and
351 pointed our URLconf at those functions. No "apps" were needed.
352
353 However, there's one requirement regarding the app convention: if you're using
354 Django's database layer (models), you must create a Django app. Models must
355 live within apps. Thus, in order to start writing our models, we'll need to
356 create a new app.
357
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
358 Within the ``mysite`` project directory, type this command to create a
359 ``books`` app::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
360
361 python manage.py startapp books
362
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
363 This command does not produce any output, but it does create a ``books``
364 directory within the ``mysite`` directory. Let's look at the contents
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
365 of that directory::
366
367 books/
368 __init__.py
369 models.py
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
370 tests.py
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
371 views.py
372
373 These files will contain the models and views for this app.
374
375 Have a look at ``models.py`` and ``views.py`` in your favorite text editor.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
376 Both files are empty, except for comments and an import in ``models.py``. This
377 is the blank slate for your Django app.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
378
379 Defining Models in Python
380 =========================
381
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
382 As we discussed earlier in this chapter, the "M" in "MTV" stands for "Model." A
383 Django model is a description of the data in your database, represented as
384 Python code. It's your data layout -- the equivalent of your SQL ``CREATE
385 TABLE`` statements -- except it's in Python instead of SQL, and it includes
386 more than just database column definitions. Django uses a model to execute SQL
387 code behind the scenes and return convenient Python data structures representing
388 the rows in your database tables. Django also uses models to represent
389 higher-level concepts that SQL can't necessarily handle.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
390
391 If you're familiar with databases, your immediate thought might be, "Isn't it
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
392 redundant to define data models in Python instead of in SQL?" Django works the
393 way it does for several reasons:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
394
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
395 * Introspection requires overhead and is imperfect. In order to provide
396 convenient data-access APIs, Django needs to know the
397 database layout *somehow*, and there are two ways of accomplishing this.
398 The first way would be to explicitly describe the data in Python, and the
399 second way would be to introspect the database at runtime to determine
400 the data models.
401
402 This second way seems cleaner, because the metadata about your tables
403 lives in only one place, but it introduces a few problems. First,
404 introspecting a database at runtime obviously requires overhead. If the
405 framework had to introspect the database each time it processed a
406 request, or even only when the Web server was initialized, this would
407 incur an unacceptable level of overhead. (While some believe that level
408 of overhead is acceptable, Django's developers aim to trim as much
409 framework overhead as possible.) Second, some databases, notably older
410 versions of MySQL, do not store sufficient metadata for accurate and
411 complete introspection.
412
413 * Writing Python is fun, and keeping everything in Python limits the number
414 of times your brain has to do a "context switch." It helps productivity
415 if you keep yourself in a single programming environment/mentality for as
416 long as possible. Having to write SQL, then Python, and then SQL again is
417 disruptive.
418
419 * Having data models stored as code rather than in your database makes it
420 easier to keep your models under version control. This way, you can
421 easily keep track of changes to your data layouts.
422
423 * SQL allows for only a certain level of metadata about a data layout. Most
424 database systems, for example, do not provide a specialized data type for
425 representing email addresses or URLs. Django models do. The advantage of
426 higher-level data types is higher productivity and more reusable code.
427
428 * SQL is inconsistent across database platforms. If you're distributing a
429 Web application, for example, it's much more pragmatic to distribute a
430 Python module that describes your data layout than separate sets of
431 ``CREATE TABLE`` statements for MySQL, PostgreSQL, and SQLite.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
432
433 A drawback of this approach, however, is that it's possible for the Python code
434 to get out of sync with what's actually in the database. If you make changes to
435 a Django model, you'll need to make the same changes inside your database to
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
436 keep your database consistent with the model. We'll discuss some strategies for
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
437 handling this problem later in this chapter.
438
439 Finally, we should note that Django includes a utility that can generate models
440 by introspecting an existing database. This is useful for quickly getting up
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
441 and running with legacy data. We'll cover this in Chapter 18.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
442
443 Your First Model
444 ================
445
446 As an ongoing example in this chapter and the next chapter, we'll focus on a
447 basic book/author/publisher data layout. We use this as our example because the
448 conceptual relationships between books, authors, and publishers are well known,
449 and this is a common data layout used in introductory SQL textbooks. You're
450 also reading a book that was written by authors and produced by a publisher!
451
452 We'll suppose the following concepts, fields, and relationships:
453
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
454 * An author has a first name, a last name and an email address.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
455
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
456 * A publisher has a name, a street address, a city, a state/province, a
457 country, and a Web site.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
458
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
459 * A book has a title and a publication date. It also has one or more
460 authors (a many-to-many relationship with authors) and a single publisher
461 (a one-to-many relationship -- aka foreign key -- to publishers).
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
462
463 The first step in using this database layout with Django is to express it as
464 Python code. In the ``models.py`` file that was created by the ``startapp``
465 command, enter the following::
466
467 from django.db import models
468
469 class Publisher(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
470 name = models.CharField(max_length=30)
471 address = models.CharField(max_length=50)
472 city = models.CharField(max_length=60)
473 state_province = models.CharField(max_length=30)
474 country = models.CharField(max_length=50)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
475 website = models.URLField()
476
477 class Author(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
478 first_name = models.CharField(max_length=30)
479 last_name = models.CharField(max_length=40)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
480 email = models.EmailField()
481
482 class Book(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
483 title = models.CharField(max_length=100)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
484 authors = models.ManyToManyField(Author)
485 publisher = models.ForeignKey(Publisher)
486 publication_date = models.DateField()
487
488 Let's quickly examine this code to cover the basics. The first thing to notice
489 is that each model is represented by a Python class that is a subclass of
490 ``django.db.models.Model``. The parent class, ``Model``, contains all the
491 machinery necessary to make these objects capable of interacting with a
492 database -- and that leaves our models responsible solely for defining their
493 fields, in a nice and compact syntax. Believe it or not, this is all the code
494 we need to write to have basic data access with Django.
495
496 Each model generally corresponds to a single database table, and each attribute
497 on a model generally corresponds to a column in that database table. The
498 attribute name corresponds to the column's name, and the type of field (e.g.,
499 ``CharField``) corresponds to the database column type (e.g., ``varchar``). For
500 example, the ``Publisher`` model is equivalent to the following table (assuming
501 PostgreSQL ``CREATE TABLE`` syntax)::
502
503 CREATE TABLE "books_publisher" (
504 "id" serial NOT NULL PRIMARY KEY,
505 "name" varchar(30) NOT NULL,
506 "address" varchar(50) NOT NULL,
507 "city" varchar(60) NOT NULL,
508 "state_province" varchar(30) NOT NULL,
509 "country" varchar(50) NOT NULL,
510 "website" varchar(200) NOT NULL
511 );
512
513 Indeed, Django can generate that ``CREATE TABLE`` statement automatically, as
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
514 we'll show you in a moment.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
515
516 The exception to the one-class-per-database-table rule is the case of
517 many-to-many relationships. In our example models, ``Book`` has a
518 ``ManyToManyField`` called ``authors``. This designates that a book has one or
519 many authors, but the ``Book`` database table doesn't get an ``authors``
520 column. Rather, Django creates an additional table -- a many-to-many "join
521 table" -- that handles the mapping of books to authors.
522
523 For a full list of field types and model syntax options, see Appendix B.
524
525 Finally, note we haven't explicitly defined a primary key in any of these
526 models. Unless you instruct it otherwise, Django automatically gives every
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
527 model an auto-incrementing integer primary key field called ``id``. Each Django
528 model is required to have a single-column primary key.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
529
530 Installing the Model
531 ====================
532
533 We've written the code; now let's create the tables in our database. In order
534 to do that, the first step is to *activate* these models in our Django project.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
535 We do that by adding the ``books`` app to the list of "installed apps" in the
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
536 settings file.
537
538 Edit the ``settings.py`` file again, and look for the ``INSTALLED_APPS``
539 setting. ``INSTALLED_APPS`` tells Django which apps are activated for a given
540 project. By default, it looks something like this::
541
542 INSTALLED_APPS = (
543 'django.contrib.auth',
544 'django.contrib.contenttypes',
545 'django.contrib.sessions',
546 'django.contrib.sites',
d64dfe8 @bharathwaaj Update admin INSTALLED_APPS requirements to 1.4
bharathwaaj authored
547 'django.contrib.messages',
548 'django.contrib.staticfiles',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
549 )
550
d64dfe8 @bharathwaaj Update admin INSTALLED_APPS requirements to 1.4
bharathwaaj authored
551 Temporarily comment out all six of those strings by putting a hash character
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
552 (``#``) in front of them. (They're included by default as a common-case
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
553 convenience, but we'll activate and discuss them in subsequent chapters.)
554 While you're at it, comment out the default ``MIDDLEWARE_CLASSES`` setting, too;
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
555 the default values in ``MIDDLEWARE_CLASSES`` depend on some of the apps we
9e97dfb @tariwan Update chapter05.rst
tariwan authored
556 just commented out. Then, add ``'books'`` to the ``INSTALLED_APPS``
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
557 list, so the setting ends up looking like this::
558
559 MIDDLEWARE_CLASSES = (
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
560 # 'django.middleware.common.CommonMiddleware',
561 # 'django.contrib.sessions.middleware.SessionMiddleware',
d64dfe8 @bharathwaaj Update admin INSTALLED_APPS requirements to 1.4
bharathwaaj authored
562 # 'django.middleware.csrf.CsrfViewMiddleware',
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
563 # 'django.contrib.auth.middleware.AuthenticationMiddleware',
d64dfe8 @bharathwaaj Update admin INSTALLED_APPS requirements to 1.4
bharathwaaj authored
564 # 'django.contrib.messages.middleware.MessageMiddleware',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
565 )
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
566
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
567 INSTALLED_APPS = (
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
568 # 'django.contrib.auth',
569 # 'django.contrib.contenttypes',
570 # 'django.contrib.sessions',
571 # 'django.contrib.sites',
9e97dfb @tariwan Update chapter05.rst
tariwan authored
572 'books',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
573 )
574
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
575 (As we mentioned last chapter when setting ``TEMPLATE_DIRS``, you'll need to be
576 sure to include the trailing comma in ``INSTALLED_APPS``, because it's a
577 single-element tuple. By the way, this book's authors prefer to put a comma
578 after *every* element of a tuple, regardless of whether the tuple has only a
579 single element. This avoids the issue of forgetting commas, and there's no
580 penalty for using that extra comma.)
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
581
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
582 ``'mysite.books'`` refers to the ``books`` app we're working on. Each app in
583 ``INSTALLED_APPS`` is represented by its full Python path -- that is, the path
584 of packages, separated by dots, leading to the app package.
585
586 Now that the Django app has been activated in the settings file, we can create
587 the database tables in our database. First, let's validate the models by
588 running this command::
589
590 python manage.py validate
591
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
592 .. SL Tested ok
593
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
594 The ``validate`` command checks whether your models' syntax and logic are
595 correct. If all is well, you'll see the message ``0 errors found``. If you
596 don't, make sure you typed in the model code correctly. The error output should
597 give you helpful information about what was wrong with the code.
598
599 Any time you think you have problems with your models, run
600 ``python manage.py validate``. It tends to catch all the common model problems.
601
602 If your models are valid, run the following command for Django to generate
603 ``CREATE TABLE`` statements for your models in the ``books`` app (with colorful
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
604 syntax highlighting available, if you're using Unix)::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
605
606 python manage.py sqlall books
607
608 In this command, ``books`` is the name of the app. It's what you specified when
609 you ran the command ``manage.py startapp``. When you run the command, you
610 should see something like this::
611
612 BEGIN;
613 CREATE TABLE "books_publisher" (
614 "id" serial NOT NULL PRIMARY KEY,
615 "name" varchar(30) NOT NULL,
616 "address" varchar(50) NOT NULL,
617 "city" varchar(60) NOT NULL,
618 "state_province" varchar(30) NOT NULL,
619 "country" varchar(50) NOT NULL,
620 "website" varchar(200) NOT NULL
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
621 )
622 ;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
623 CREATE TABLE "books_author" (
624 "id" serial NOT NULL PRIMARY KEY,
625 "first_name" varchar(30) NOT NULL,
626 "last_name" varchar(40) NOT NULL,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
627 "email" varchar(75) NOT NULL
628 )
629 ;
630 CREATE TABLE "books_book" (
631 "id" serial NOT NULL PRIMARY KEY,
632 "title" varchar(100) NOT NULL,
633 "publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id") DEFERRABLE INITIALLY DEFERRED,
634 "publication_date" date NOT NULL
635 )
636 ;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
637 CREATE TABLE "books_book_authors" (
638 "id" serial NOT NULL PRIMARY KEY,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
639 "book_id" integer NOT NULL REFERENCES "books_book" ("id") DEFERRABLE INITIALLY DEFERRED,
640 "author_id" integer NOT NULL REFERENCES "books_author" ("id") DEFERRABLE INITIALLY DEFERRED,
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
641 UNIQUE ("book_id", "author_id")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
642 )
643 ;
644 CREATE INDEX "books_book_publisher_id" ON "books_book" ("publisher_id");
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
645 COMMIT;
646
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
647 .. SL Tested ok (sqlall output for postgres matches that shown here)
648
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
649 Note the following:
650
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
651 * Table names are automatically generated by combining the name of the app
652 (``books``) and the lowercase name of the model (``publisher``,
653 ``book``, and ``author``). You can override this behavior, as detailed
654 in Appendix B.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
655
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
656 * As we mentioned earlier, Django adds a primary key for each table
657 automatically -- the ``id`` fields. You can override this, too.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
658
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
659 * By convention, Django appends ``"_id"`` to the foreign key field name. As
660 you might have guessed, you can override this behavior, too.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
661
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
662 * The foreign key relationship is made explicit by a ``REFERENCES``
663 statement.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
664
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
665 * These ``CREATE TABLE`` statements are tailored to the database you're
666 using, so database-specific field types such as ``auto_increment``
667 (MySQL), ``serial`` (PostgreSQL), or ``integer primary key`` (SQLite) are
668 handled for you automatically. The same goes for quoting of column names
669 (e.g., using double quotes or single quotes). This example output is in
670 PostgreSQL syntax.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
671
672 The ``sqlall`` command doesn't actually create the tables or otherwise touch
673 your database -- it just prints output to the screen so you can see what SQL
674 Django would execute if you asked it. If you wanted to, you could copy and
675 paste this SQL into your database client, or use Unix pipes to pass it
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
676 directly (e.g., ``python manage.py sqlall books | psql mydb``). However, Django
677 provides an easier way of committing the SQL to the database: the ``syncdb``
678 command::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
679
680 python manage.py syncdb
681
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
682 Run that command, and you'll see something like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
683
684 Creating table books_publisher
685 Creating table books_author
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
686 Creating table books_book
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
687 Installing index for books.Book model
688
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
689 .. SL Tested ok
690
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
691 The ``syncdb`` command is a simple "sync" of your models to your database. It
692 looks at all of the models in each app in your ``INSTALLED_APPS`` setting,
693 checks the database to see whether the appropriate tables exist yet, and
694 creates the tables if they don't yet exist. Note that ``syncdb`` does *not*
695 sync changes in models or deletions of models; if you make a change to a model
696 or delete a model, and you want to update the database, ``syncdb`` will not
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
697 handle that. (More on this in the "Making Changes to a Database Schema" section
698 toward the end of this chapter.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
699
700 If you run ``python manage.py syncdb`` again, nothing happens, because you
701 haven't added any models to the ``books`` app or added any apps to
702 ``INSTALLED_APPS``. Ergo, it's always safe to run ``python manage.py syncdb``
703 -- it won't clobber things.
704
705 If you're interested, take a moment to dive into your database server's
706 command-line client and see the database tables Django created. You can
707 manually run the command-line client (e.g., ``psql`` for PostgreSQL) or
708 you can run the command ``python manage.py dbshell``, which will figure out
709 which command-line client to run, depending on your ``DATABASE_SERVER``
710 setting. The latter is almost always more convenient.
711
712 Basic Data Access
713 =================
714
715 Once you've created a model, Django automatically provides a high-level Python
716 API for working with those models. Try it out by running
717 ``python manage.py shell`` and typing the following::
718
719 >>> from books.models import Publisher
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
720 >>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
721 ... city='Berkeley', state_province='CA', country='U.S.A.',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
722 ... website='http://www.apress.com/')
723 >>> p1.save()
724 >>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
725 ... city='Cambridge', state_province='MA', country='U.S.A.',
726 ... website='http://www.oreilly.com/')
727 >>> p2.save()
728 >>> publisher_list = Publisher.objects.all()
729 >>> publisher_list
730 [<Publisher: Publisher object>, <Publisher: Publisher object>]
731
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
732 .. SL Tested ok
733
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
734 These few lines of code accomplish quite a bit. Here are the highlights:
735
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
736 * First, we import our ``Publisher`` model class. This lets us interact
737 with the database table that contains publishers.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
738
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
739 * We create a ``Publisher`` object by instantiating it with values for
740 each field -- ``name``, ``address``, etc.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
741
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
742 * To save the object to the database, call its ``save()`` method. Behind
743 the scenes, Django executes an SQL ``INSERT`` statement here.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
744
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
745 * To retrieve publishers from the database, use the attribute
746 ``Publisher.objects``, which you can think of as a set of all publishers.
747 Fetch a list of *all* ``Publisher`` objects in the database with the
748 statement ``Publisher.objects.all()``. Behind the scenes, Django executes
749 an SQL ``SELECT`` statement here.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
750
751 One thing is worth mentioning, in case it wasn't clear from this example. When
752 you're creating objects using the Django model API, Django doesn't save the
753 objects to the database until you call the ``save()`` method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
754
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
755 p1 = Publisher(...)
756 # At this point, p1 is not saved to the database yet!
757 p1.save()
758 # Now it is.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
759
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
760 If you want to create an object and save it to the database in a single step,
761 use the ``objects.create()`` method. This example is equivalent to the example
762 above::
763
764 >>> p1 = Publisher.objects.create(name='Apress',
765 ... address='2855 Telegraph Avenue',
766 ... city='Berkeley', state_province='CA', country='U.S.A.',
767 ... website='http://www.apress.com/')
768 >>> p2 = Publisher.objects.create(name="O'Reilly",
769 ... address='10 Fawcett St.', city='Cambridge',
770 ... state_province='MA', country='U.S.A.',
771 ... website='http://www.oreilly.com/')
772 >>> publisher_list = Publisher.objects.all()
773 >>> publisher_list
774
775 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
776
777 Naturally, you can do quite a lot with the Django database API -- but first,
778 let's take care of a small annoyance.
779
780 Adding Model String Representations
781 ===================================
782
783 When we printed out the list of publishers, all we got was this
784 unhelpful display that makes it difficult to tell the ``Publisher`` objects
785 apart::
786
787 [<Publisher: Publisher object>, <Publisher: Publisher object>]
788
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
789 We can fix this easily by adding a method called ``__unicode__()`` to our
790 ``Publisher`` class. A ``__unicode__()`` method tells Python how to display the
791 "unicode" representation of an object. You can see this in action by adding a
792 ``__unicode__()`` method to the three models:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
793
794 .. parsed-literal::
795
796 from django.db import models
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
797
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
798 class Publisher(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
799 name = models.CharField(max_length=30)
800 address = models.CharField(max_length=50)
801 city = models.CharField(max_length=60)
802 state_province = models.CharField(max_length=30)
803 country = models.CharField(max_length=50)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
804 website = models.URLField()
805
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
806 **def __unicode__(self):**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
807 **return self.name**
808
809 class Author(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
810 first_name = models.CharField(max_length=30)
811 last_name = models.CharField(max_length=40)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
812 email = models.EmailField()
813
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
814 **def __unicode__(self):**
815 **return u'%s %s' % (self.first_name, self.last_name)**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
816
817 class Book(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
818 title = models.CharField(max_length=100)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
819 authors = models.ManyToManyField(Author)
820 publisher = models.ForeignKey(Publisher)
821 publication_date = models.DateField()
822
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
823 **def __unicode__(self):**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
824 **return self.title**
825
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
826 As you can see, a ``__unicode__()`` method can do whatever it needs to do in order
827 to return a representation of an object. Here, the ``__unicode__()`` methods for
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
828 ``Publisher`` and ``Book`` simply return the object's name and title,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
829 respectively, but the ``__unicode__()`` for ``Author`` is slightly more complex --
830 it pieces together the ``first_name`` and ``last_name`` fields, separated by a
831 space.
832
833 The only requirement for ``__unicode__()`` is that it return a Unicode object.
834 If ``__unicode__()`` doesn't return a Unicode object -- if it returns, say, an
835 integer -- then Python will raise a ``TypeError`` with a message like
836 ``"coercing to Unicode: need string or buffer, int found"``.
837
838 .. admonition:: Unicode objects
839
840 What are Unicode objects?
841
842 You can think of a Unicode object as a Python string that can handle more
843 than a million different types of characters, from accented versions of
844 Latin characters to non-Latin characters to curly quotes and obscure
845 symbols.
846
847 Normal Python strings are *encoded*, which means they use an encoding such
848 as ASCII, ISO-8859-1 or UTF-8. If you're storing fancy characters (anything
849 beyond the standard 128 ASCII characters such as 0-9 and A-Z) in a normal
850 Python string, you have to keep track of which encoding your string is
851 using, or the fancy characters might appear messed up when they're
852 displayed or printed. Problems occur when you have data that's stored in
853 one encoding and you try to combine it with data in a different encoding,
854 or you try to display it in an application that assumes a certain encoding.
855 We've all seen Web pages and e-mails that are littered with "??? ??????"
856 or other characters in odd places; that generally suggests there's an
857 encoding problem.
858
859 Unicode objects, however, have no encoding; they use a consistent,
860 universal set of characters called, well, "Unicode." When you deal with
861 Unicode objects in Python, you can mix and match them safely without having
862 to worry about encoding issues.
863
864 Django uses Unicode objects throughout the framework. Model objects are
865 retrieved as Unicode objects, views interact with Unicode data, and
866 templates are rendered as Unicode. Generally, you won't have to worry about
867 making sure your encodings are right; things should just work.
868
869 Note that this has been a *very* high-level, dumbed down overview of
870 Unicode objects, and you owe it to yourself to learn more about the topic.
871 A good place to start is http://www.joelonsoftware.com/articles/Unicode.html .
872
873 For the ``__unicode__()`` changes to take effect, exit out of the Python shell
874 and enter it again with ``python manage.py shell``. (This is the simplest way
875 to make code changes take effect.) Now the list of ``Publisher`` objects is
876 much easier to understand::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
877
878 >>> from books.models import Publisher
879 >>> publisher_list = Publisher.objects.all()
880 >>> publisher_list
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
881 [<Publisher: Apress>, <Publisher: O'Reilly>]
882
883 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
884
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
885 Make sure any model you define has a ``__unicode__()`` method -- not only for
886 your own convenience when using the interactive interpreter, but also because
887 Django uses the output of ``__unicode__()`` in several places when it needs to
888 display objects.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
889
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
890 Finally, note that ``__unicode__()`` is a good example of adding *behavior* to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
891 models. A Django model describes more than the database table layout for an
892 object; it also describes any functionality that object knows how to do.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
893 ``__unicode__()`` is one example of such functionality -- a model knows how to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
894 display itself.
895
896 Inserting and Updating Data
897 ===========================
898
899 You've already seen this done: to insert a row into your database, first create
900 an instance of your model using keyword arguments, like so::
901
902 >>> p = Publisher(name='Apress',
903 ... address='2855 Telegraph Ave.',
904 ... city='Berkeley',
905 ... state_province='CA',
906 ... country='U.S.A.',
907 ... website='http://www.apress.com/')
908
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
909 As we noted above, this act of instantiating a model class does *not* touch
910 the database. The record isn't saved into the database until you call
911 ``save()``, like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
912
913 >>> p.save()
914
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
915 .. SL Tested ok
916
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
917 In SQL, this can roughly be translated into the following::
918
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
919 INSERT INTO books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
920 (name, address, city, state_province, country, website)
921 VALUES
922 ('Apress', '2855 Telegraph Ave.', 'Berkeley', 'CA',
923 'U.S.A.', 'http://www.apress.com/');
924
925 Because the ``Publisher`` model uses an autoincrementing primary key ``id``,
926 the initial call to ``save()`` does one more thing: it calculates the primary
927 key value for the record and sets it to the ``id`` attribute on the instance::
928
929 >>> p.id
930 52 # this will differ based on your own data
931
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
932 .. SL Should be '52L' to match actual output.
933
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
934 Subsequent calls to ``save()`` will save the record in place, without creating
935 a new record (i.e., performing an SQL ``UPDATE`` statement instead of an
936 ``INSERT``)::
937
938 >>> p.name = 'Apress Publishing'
939 >>> p.save()
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
940
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
941 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
942
943 The preceding ``save()`` statement will result in roughly the following SQL::
944
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
945 UPDATE books_publisher SET
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
946 name = 'Apress Publishing',
947 address = '2855 Telegraph Ave.',
948 city = 'Berkeley',
949 state_province = 'CA',
950 country = 'U.S.A.',
951 website = 'http://www.apress.com'
952 WHERE id = 52;
953
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
954 Yes, note that *all* of the fields will be updated, not just the ones that have
955 been changed. Depending on your application, this may cause a race condition.
956 See "Updating Multiple Objects in One Statement" below to find out how to
957 execute this (slightly different) query::
958
959 UPDATE books_publisher SET
960 name = 'Apress Publishing'
961 WHERE id=52;
962
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
963 Selecting Objects
964 =================
965
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
966 Knowing how to create and update database records is essential, but chances are
967 that the Web applications you'll build will be doing more querying of existing
968 objects than creating new ones. We've already seen a way to retrieve *every*
969 record for a given model::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
970
971 >>> Publisher.objects.all()
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
972 [<Publisher: Apress>, <Publisher: O'Reilly>]
973
974 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
975
976 This roughly translates to this SQL::
977
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
978 SELECT id, name, address, city, state_province, country, website
979 FROM books_publisher;
980
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
981 .. note::
982
983 Notice that Django doesn't use ``SELECT *`` when looking up data and instead
984 lists all fields explicitly. This is by design: in certain circumstances
985 ``SELECT *`` can be slower, and (more important) listing fields more closely
986 follows one tenet of the Zen of Python: "Explicit is better than implicit."
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
987
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
988 For more on the Zen of Python, try typing ``import this`` at a Python
989 prompt.
990
991 Let's take a close look at each part of this ``Publisher.objects.all()`` line:
992
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
993 * First, we have the model we defined, ``Publisher``. No surprise here: when
994 you want to look up data, you use the model for that data.
995
996 * Next, we have the ``objects`` attribute. This is called a *manager*.
997 Managers are discussed in detail in Chapter 10. For now, all you need to
998 know is that managers take care of all "table-level" operations on data
999 including, most important, data lookup.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1000
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1001 All models automatically get a ``objects`` manager; you'll use it
1002 any time you want to look up model instances.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1003
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1004 * Finally, we have ``all()``. This is a method on the ``objects`` manager
1005 that returns all the rows in the database. Though this object *looks*
1006 like a list, it's actually a *QuerySet* -- an object that represents a
1007 specific set of rows from the database. Appendix C deals with QuerySets
1008 in detail. For the rest of this chapter, we'll just treat them like the
1009 lists they emulate.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1010
1011 Any database lookup is going to follow this general pattern -- we'll call methods on
1012 the manager attached to the model we want to query against.
1013
1014 Filtering Data
1015 --------------
1016
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1017 Naturally, it's rare to want to select *everything* from a database at once; in
1018 most cases, you'll want to deal with a subset of your data. In the Django API,
1019 you can filter your data using the ``filter()`` method::
1020
1021 >>> Publisher.objects.filter(name='Apress')
1022 [<Publisher: Apress>]
1023
1024 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1025
1026 ``filter()`` takes keyword arguments that get translated into the appropriate
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1027 SQL ``WHERE`` clauses. The preceding example would get translated into
1028 something like this::
1029
1030 SELECT id, name, address, city, state_province, country, website
1031 FROM books_publisher
1032 WHERE name = 'Apress';
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1033
1034 You can pass multiple arguments into ``filter()`` to narrow down things further::
1035
1036 >>> Publisher.objects.filter(country="U.S.A.", state_province="CA")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1037 [<Publisher: Apress>]
1038
1039 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1040
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1041 Those multiple arguments get translated into SQL ``AND`` clauses. Thus, the
1042 example in the code snippet translates into the following::
1043
1044 SELECT id, name, address, city, state_province, country, website
1045 FROM books_publisher
1046 WHERE country = 'U.S.A.'
1047 AND state_province = 'CA';
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1048
1049 Notice that by default the lookups use the SQL ``=`` operator to do exact match
1050 lookups. Other lookup types are available::
1051
1052 >>> Publisher.objects.filter(name__contains="press")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1053 [<Publisher: Apress>]
1054
1055 .. SL Tested ok
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1056
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1057 That's a *double* underscore there between ``name`` and ``contains``. Like
1058 Python itself, Django uses the double underscore to signal that something
1059 "magic" is happening -- here, the ``__contains`` part gets translated by Django
1060 into a SQL ``LIKE`` statement::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1061
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1062 SELECT id, name, address, city, state_province, country, website
1063 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1064 WHERE name LIKE '%press%';
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1065
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1066 Many other types of lookups are available, including ``icontains``
1067 (case-insensitive ``LIKE``), ``startswith`` and ``endswith``, and ``range`` (SQL
1068 ``BETWEEN`` queries). Appendix C describes all of these lookup types in detail.
1069
1070 Retrieving Single Objects
1071 -------------------------
1072
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1073 The ``filter()`` examples above all returned a ``QuerySet``, which you can
1074 treat like a list. Sometimes it's more convenient to fetch only a single object,
1075 as opposed to a list. That's what the ``get()`` method is for::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1076
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1077 >>> Publisher.objects.get(name="Apress")
1078 <Publisher: Apress>
1079
1080 .. SL Tested ok
1081
1082 Instead of a list (rather, ``QuerySet``), only a single object is returned.
1083 Because of that, a query resulting in multiple objects will cause an
1084 exception::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1085
1086 >>> Publisher.objects.get(country="U.S.A.")
1087 Traceback (most recent call last):
1088 ...
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1089 MultipleObjectsReturned: get() returned more than one Publisher --
1090 it returned 2! Lookup parameters were {'country': 'U.S.A.'}
1091
1092 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1093
1094 A query that returns no objects also causes an exception::
1095
1096 >>> Publisher.objects.get(name="Penguin")
1097 Traceback (most recent call last):
1098 ...
1099 DoesNotExist: Publisher matching query does not exist.
1100
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1101 .. SL Tested ok
1102
1103 The ``DoesNotExist`` exception is an attribute of the model's class --
1104 ``Publisher.DoesNotExist``. In your applications, you'll want to trap these
1105 exceptions, like this::
1106
1107 try:
1108 p = Publisher.objects.get(name='Apress')
1109 except Publisher.DoesNotExist:
1110 print "Apress isn't in the database yet."
1111 else:
1112 print "Apress is in the database."
1113
1114 .. SL Tested ok
1115
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1116 Ordering Data
1117 -------------
1118
1119 As you play around with the previous examples, you might discover that the objects
1120 are being returned in a seemingly random order. You aren't imagining things; so
1121 far we haven't told the database how to order its results, so we're simply
1122 getting back data in some arbitrary order chosen by the database.
1123
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1124 In your Django applications, you'll probably want to order your results
1125 according to a certain value -- say, alphabetically. To do this, use the
1126 ``order_by()`` method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1127
1128 >>> Publisher.objects.order_by("name")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1129 [<Publisher: Apress>, <Publisher: O'Reilly>]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1130
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1131 .. SL Tested ok
1132
1133 This doesn't look much different from the earlier ``all()`` example, but the
1134 SQL now includes a specific ordering::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1135
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1136 SELECT id, name, address, city, state_province, country, website
1137 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1138 ORDER BY name;
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1139
1140 You can order by any field you like::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1141
1142 >>> Publisher.objects.order_by("address")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1143 [<Publisher: O'Reilly>, <Publisher: Apress>]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1144
1145 >>> Publisher.objects.order_by("state_province")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1146 [<Publisher: Apress>, <Publisher: O'Reilly>]
1147
1148 .. SL Tested ok
1149
1150 To order by multiple fields (where the second field is used to disambiguate
1151 ordering in cases where the first is the same), use multiple arguments::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1152
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1153 >>> Publisher.objects.order_by("state_province", "address")
1154 [<Publisher: Apress>, <Publisher: O'Reilly>]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1155
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1156 .. SL Tested ok
1157
1158 You can also specify reverse ordering by prefixing the field name with a ``-``
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1159 (that's a minus character)::
1160
1161 >>> Publisher.objects.order_by("-name")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1162 [<Publisher: O'Reilly>, <Publisher: Apress>]
1163
1164 .. SL Tested ok
1165
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1166 While this flexibility is useful, using ``order_by()`` all the time can be quite
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1167 repetitive. Most of the time you'll have a particular field you usually want
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1168 to order by. In these cases, Django lets you specify a default ordering in the
1169 model:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1170
1171 .. parsed-literal::
1172
1173 class Publisher(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1174 name = models.CharField(max_length=30)
1175 address = models.CharField(max_length=50)
1176 city = models.CharField(max_length=60)
1177 state_province = models.CharField(max_length=30)
1178 country = models.CharField(max_length=50)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1179 website = models.URLField()
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1180
1181 def __unicode__(self):
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1182 return self.name
1183
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1184 **class Meta:**
1185 **ordering = ['name']**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1186
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1187 Here, we've introduced a new concept: the ``class Meta``, which is a class
1188 that's embedded within the ``Publisher`` class definition (i.e., it's indented
1189 to be within ``class Publisher``). You can use this ``Meta`` class on any model
1190 to specify various model-specific options. A full reference of ``Meta`` options
1191 is available in Appendix B, but for now, we're concerned with the ``ordering``
1192 option. If you specify this, it tells Django that unless an ordering is given
1193 explicitly with ``order_by()``, all ``Publisher`` objects should be ordered by
1194 the ``name`` field whenever they're retrieved with the Django database API.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1195
1196 Chaining Lookups
1197 ----------------
1198
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1199 You've seen how you can filter data, and you've seen how you can order it. Often, of course,
1200 you'll need to do both. In these cases, you simply "chain" the lookups together::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1201
1202 >>> Publisher.objects.filter(country="U.S.A.").order_by("-name")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1203 [<Publisher: O'Reilly>, <Publisher: Apress>]
1204
1205 .. SL Tested ok
1206
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1207 As you might expect, this translates to a SQL query with both a ``WHERE`` and an
1208 ``ORDER BY``::
1209
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1210 SELECT id, name, address, city, state_province, country, website
1211 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1212 WHERE country = 'U.S.A'
1213 ORDER BY name DESC;
1214
1215 Slicing Data
1216 ------------
1217
1218 Another common need is to look up only a fixed number of rows. Imagine you have thousands
1219 of publishers in your database, but you want to display only the first one. You can do this
1220 using Python's standard list slicing syntax::
1221
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1222 >>> Publisher.objects.order_by('name')[0]
1223 <Publisher: Apress>
1224
1225 .. SL Tested ok
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1226
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1227 This translates roughly to::
1228
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1229 SELECT id, name, address, city, state_province, country, website
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1230 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1231 ORDER BY name
1232 LIMIT 1;
1233
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1234 Similarly, you can retrieve a specific subset of data using Python's
1235 range-slicing syntax::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1236
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1237 >>> Publisher.objects.order_by('name')[0:2]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1238
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1239 .. SL Tested ok (but should show expected output?)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1240
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1241 This returns two objects, translating roughly to::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1242
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1243 SELECT id, name, address, city, state_province, country, website
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1244 FROM books_publisher
1245 ORDER BY name
1246 OFFSET 0 LIMIT 2;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1247
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1248 Note that negative slicing is *not* supported::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1249
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1250 >>> Publisher.objects.order_by('name')[-1]
1251 Traceback (most recent call last):
1252 ...
1253 AssertionError: Negative indexing is not supported.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1254
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1255 This is easy to get around, though. Just change the ``order_by()`` statement,
1256 like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1257
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1258 >>> Publisher.objects.order_by('-name')[0]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1259
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1260 Updating Multiple Objects in One Statement
1261 ------------------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1262
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1263 We pointed out in the "Inserting and Updating Data" section that the model
1264 ``save()`` method updates *all* columns in a row. Depending on your
1265 application, you may want to update only a subset of columns.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1266
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1267 For example, let's say we want to update the Apress ``Publisher`` to change
1268 the name from ``'Apress'`` to ``'Apress Publishing'``. Using ``save()``, it
1269 would look something like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1270
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1271 >>> p = Publisher.objects.get(name='Apress')
1272 >>> p.name = 'Apress Publishing'
1273 >>> p.save()
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1274
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1275 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1276
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1277 This roughly translates to the following SQL::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1278
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1279 SELECT id, name, address, city, state_province, country, website
1280 FROM books_publisher
1281 WHERE name = 'Apress';
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1282
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1283 UPDATE books_publisher SET
1284 name = 'Apress Publishing',
1285 address = '2855 Telegraph Ave.',
1286 city = 'Berkeley',
1287 state_province = 'CA',
1288 country = 'U.S.A.',
1289 website = 'http://www.apress.com'
1290 WHERE id = 52;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1291
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1292 (Note that this example assumes Apress has a publisher ID of ``52``.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1293
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1294 You can see in this example that Django's ``save()`` method sets *all* of the
1295 column values, not just the ``name`` column. If you're in an environment where
1296 other columns of the database might change due to some other process, it's
1297 smarter to change *only* the column you need to change. To do this, use the
1298 ``update()`` method on ``QuerySet`` objects. Here's an example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1299
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1300 >>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1301
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1302 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1303
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1304 The SQL translation here is much more efficient and has no chance of race
1305 conditions::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1306
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1307 UPDATE books_publisher
1308 SET name = 'Apress Publishing'
1309 WHERE id = 52;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1310
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1311 The ``update()`` method works on any ``QuerySet``, which means you can edit
1312 multiple records in bulk. Here's how you might change the ``country`` from
1313 ``'U.S.A.'`` to ``USA`` in each ``Publisher`` record::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1314
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1315 >>> Publisher.objects.all().update(country='USA')
1316 2
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1317
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1318 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1319
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1320 The ``update()`` method has a return value -- an integer representing how many
1321 records changed. In the above example, we got ``2``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1322
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1323 Deleting Objects
1324 ================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1325
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1326 To delete an object from your database, simply call the object's ``delete()``
1327 method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1328
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1329 >>> p = Publisher.objects.get(name="O'Reilly")
1330 >>> p.delete()
1331 >>> Publisher.objects.all()
1332 [<Publisher: Apress Publishing>]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1333
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1334 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1335
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1336 You can also delete objects in bulk by calling ``delete()`` on the result of
1337 any ``QuerySet``. This is similar to the ``update()`` method we showed in the
1338 last section::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1339
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1340 >>> Publisher.objects.filter(country='USA').delete()
1341 >>> Publisher.objects.all().delete()
1342 >>> Publisher.objects.all()
1343 []
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1344
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1345 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1346
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1347 Be careful deleting your data! As a precaution against deleting all of the data
1348 in a particular table, Django requires you to explicitly use ``all()`` if you
1349 want to delete *everything* in your table. For example, this won't work::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1350
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1351 >>> Publisher.objects.delete()
1352 Traceback (most recent call last):
1353 File "<console>", line 1, in <module>
1354 AttributeError: 'Manager' object has no attribute 'delete'
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1355
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1356 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1357
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1358 But it'll work if you add the ``all()`` method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1359
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1360 >>> Publisher.objects.all().delete()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1361
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1362 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1363
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1364 If you're just deleting a subset of your data, you don't need to include
1365 ``all()``. To repeat a previous example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1366
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1367 >>> Publisher.objects.filter(country='USA').delete()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1368
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1369 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1370
1371 What's Next?
1372 ============
1373
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1374 Having read this chapter, you have enough knowledge of Django models to be able
1375 to write basic database applications. Chapter 10 will provide some information
1376 on more advanced usage of Django's database layer.
1377
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1378 Once you've defined your models, the next step is to populate your database
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1379 with data. You might have legacy data, in which case Chapter 18 will give you
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1380 advice about integrating with legacy databases. You might rely on site users
1381 to supply your data, in which case Chapter 7 will teach you how to process
1382 user-submitted form data.
1383
1384 But in some cases, you or your team might need to enter data manually, in which
1385 case it would be helpful to have a Web-based interface for entering and
b7009a7 @jay754 Update 05.rst
jay754 authored
1386 managing data. The next chapter `Chapter 6`_ covers Django's admin interface, which exists
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1387 precisely for that reason.
ebd3449 @jay754 Broken links fix on all chapters
jay754 authored
1388
01f8ebc @belgianguy Removed trailing slash, rst to html
belgianguy authored
1389 .. _Chapter 6: chapter06.html
Something went wrong with that request. Please try again.