Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 1384 lines (1050 sloc) 59.059 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',
547 )
548
549 Temporarily comment out all four of those strings by putting a hash character
550 (``#``) 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
551 convenience, but we'll activate and discuss them in subsequent chapters.)
552 While you're at it, comment out the default ``MIDDLEWARE_CLASSES`` setting, too;
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
553 the default values in ``MIDDLEWARE_CLASSES`` depend on some of the apps we
554 just commented out. Then, add ``'mysite.books'`` to the ``INSTALLED_APPS``
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
555 list, so the setting ends up looking like this::
556
557 MIDDLEWARE_CLASSES = (
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
558 # 'django.middleware.common.CommonMiddleware',
559 # 'django.contrib.sessions.middleware.SessionMiddleware',
560 # 'django.contrib.auth.middleware.AuthenticationMiddleware',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
561 )
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
562
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
563 INSTALLED_APPS = (
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
564 # 'django.contrib.auth',
565 # 'django.contrib.contenttypes',
566 # 'django.contrib.sessions',
567 # 'django.contrib.sites',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
568 'mysite.books',
569 )
570
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
571 (As we mentioned last chapter when setting ``TEMPLATE_DIRS``, you'll need to be
572 sure to include the trailing comma in ``INSTALLED_APPS``, because it's a
573 single-element tuple. By the way, this book's authors prefer to put a comma
574 after *every* element of a tuple, regardless of whether the tuple has only a
575 single element. This avoids the issue of forgetting commas, and there's no
576 penalty for using that extra comma.)
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
577
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
578 ``'mysite.books'`` refers to the ``books`` app we're working on. Each app in
579 ``INSTALLED_APPS`` is represented by its full Python path -- that is, the path
580 of packages, separated by dots, leading to the app package.
581
582 Now that the Django app has been activated in the settings file, we can create
583 the database tables in our database. First, let's validate the models by
584 running this command::
585
586 python manage.py validate
587
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
588 .. SL Tested ok
589
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
590 The ``validate`` command checks whether your models' syntax and logic are
591 correct. If all is well, you'll see the message ``0 errors found``. If you
592 don't, make sure you typed in the model code correctly. The error output should
593 give you helpful information about what was wrong with the code.
594
595 Any time you think you have problems with your models, run
596 ``python manage.py validate``. It tends to catch all the common model problems.
597
598 If your models are valid, run the following command for Django to generate
599 ``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
600 syntax highlighting available, if you're using Unix)::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
601
602 python manage.py sqlall books
603
604 In this command, ``books`` is the name of the app. It's what you specified when
605 you ran the command ``manage.py startapp``. When you run the command, you
606 should see something like this::
607
608 BEGIN;
609 CREATE TABLE "books_publisher" (
610 "id" serial NOT NULL PRIMARY KEY,
611 "name" varchar(30) NOT NULL,
612 "address" varchar(50) NOT NULL,
613 "city" varchar(60) NOT NULL,
614 "state_province" varchar(30) NOT NULL,
615 "country" varchar(50) NOT NULL,
616 "website" varchar(200) NOT NULL
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
617 )
618 ;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
619 CREATE TABLE "books_author" (
620 "id" serial NOT NULL PRIMARY KEY,
621 "first_name" varchar(30) NOT NULL,
622 "last_name" varchar(40) NOT NULL,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
623 "email" varchar(75) NOT NULL
624 )
625 ;
626 CREATE TABLE "books_book" (
627 "id" serial NOT NULL PRIMARY KEY,
628 "title" varchar(100) NOT NULL,
629 "publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id") DEFERRABLE INITIALLY DEFERRED,
630 "publication_date" date NOT NULL
631 )
632 ;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
633 CREATE TABLE "books_book_authors" (
634 "id" serial NOT NULL PRIMARY KEY,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
635 "book_id" integer NOT NULL REFERENCES "books_book" ("id") DEFERRABLE INITIALLY DEFERRED,
636 "author_id" integer NOT NULL REFERENCES "books_author" ("id") DEFERRABLE INITIALLY DEFERRED,
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
637 UNIQUE ("book_id", "author_id")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
638 )
639 ;
640 CREATE INDEX "books_book_publisher_id" ON "books_book" ("publisher_id");
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
641 COMMIT;
642
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
643 .. SL Tested ok (sqlall output for postgres matches that shown here)
644
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
645 Note the following:
646
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
647 * Table names are automatically generated by combining the name of the app
648 (``books``) and the lowercase name of the model (``publisher``,
649 ``book``, and ``author``). You can override this behavior, as detailed
650 in Appendix B.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
651
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
652 * As we mentioned earlier, Django adds a primary key for each table
653 automatically -- the ``id`` fields. You can override this, too.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
654
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
655 * By convention, Django appends ``"_id"`` to the foreign key field name. As
656 you might have guessed, you can override this behavior, too.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
657
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
658 * The foreign key relationship is made explicit by a ``REFERENCES``
659 statement.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
660
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
661 * These ``CREATE TABLE`` statements are tailored to the database you're
662 using, so database-specific field types such as ``auto_increment``
663 (MySQL), ``serial`` (PostgreSQL), or ``integer primary key`` (SQLite) are
664 handled for you automatically. The same goes for quoting of column names
665 (e.g., using double quotes or single quotes). This example output is in
666 PostgreSQL syntax.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
667
668 The ``sqlall`` command doesn't actually create the tables or otherwise touch
669 your database -- it just prints output to the screen so you can see what SQL
670 Django would execute if you asked it. If you wanted to, you could copy and
671 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
672 directly (e.g., ``python manage.py sqlall books | psql mydb``). However, Django
673 provides an easier way of committing the SQL to the database: the ``syncdb``
674 command::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
675
676 python manage.py syncdb
677
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
678 Run that command, and you'll see something like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
679
680 Creating table books_publisher
681 Creating table books_author
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
682 Creating table books_book
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
683 Installing index for books.Book model
684
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
685 .. SL Tested ok
686
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
687 The ``syncdb`` command is a simple "sync" of your models to your database. It
688 looks at all of the models in each app in your ``INSTALLED_APPS`` setting,
689 checks the database to see whether the appropriate tables exist yet, and
690 creates the tables if they don't yet exist. Note that ``syncdb`` does *not*
691 sync changes in models or deletions of models; if you make a change to a model
692 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
693 handle that. (More on this in the "Making Changes to a Database Schema" section
694 toward the end of this chapter.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
695
696 If you run ``python manage.py syncdb`` again, nothing happens, because you
697 haven't added any models to the ``books`` app or added any apps to
698 ``INSTALLED_APPS``. Ergo, it's always safe to run ``python manage.py syncdb``
699 -- it won't clobber things.
700
701 If you're interested, take a moment to dive into your database server's
702 command-line client and see the database tables Django created. You can
703 manually run the command-line client (e.g., ``psql`` for PostgreSQL) or
704 you can run the command ``python manage.py dbshell``, which will figure out
705 which command-line client to run, depending on your ``DATABASE_SERVER``
706 setting. The latter is almost always more convenient.
707
708 Basic Data Access
709 =================
710
711 Once you've created a model, Django automatically provides a high-level Python
712 API for working with those models. Try it out by running
713 ``python manage.py shell`` and typing the following::
714
715 >>> from books.models import Publisher
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
716 >>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
717 ... city='Berkeley', state_province='CA', country='U.S.A.',
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
718 ... website='http://www.apress.com/')
719 >>> p1.save()
720 >>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
721 ... city='Cambridge', state_province='MA', country='U.S.A.',
722 ... website='http://www.oreilly.com/')
723 >>> p2.save()
724 >>> publisher_list = Publisher.objects.all()
725 >>> publisher_list
726 [<Publisher: Publisher object>, <Publisher: Publisher object>]
727
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
728 .. SL Tested ok
729
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
730 These few lines of code accomplish quite a bit. Here are the highlights:
731
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
732 * First, we import our ``Publisher`` model class. This lets us interact
733 with the database table that contains publishers.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
734
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
735 * We create a ``Publisher`` object by instantiating it with values for
736 each field -- ``name``, ``address``, etc.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
737
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
738 * To save the object to the database, call its ``save()`` method. Behind
739 the scenes, Django executes an SQL ``INSERT`` statement here.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
740
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
741 * To retrieve publishers from the database, use the attribute
742 ``Publisher.objects``, which you can think of as a set of all publishers.
743 Fetch a list of *all* ``Publisher`` objects in the database with the
744 statement ``Publisher.objects.all()``. Behind the scenes, Django executes
745 an SQL ``SELECT`` statement here.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
746
747 One thing is worth mentioning, in case it wasn't clear from this example. When
748 you're creating objects using the Django model API, Django doesn't save the
749 objects to the database until you call the ``save()`` method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
750
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
751 p1 = Publisher(...)
752 # At this point, p1 is not saved to the database yet!
753 p1.save()
754 # Now it is.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
755
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
756 If you want to create an object and save it to the database in a single step,
757 use the ``objects.create()`` method. This example is equivalent to the example
758 above::
759
760 >>> p1 = Publisher.objects.create(name='Apress',
761 ... address='2855 Telegraph Avenue',
762 ... city='Berkeley', state_province='CA', country='U.S.A.',
763 ... website='http://www.apress.com/')
764 >>> p2 = Publisher.objects.create(name="O'Reilly",
765 ... address='10 Fawcett St.', city='Cambridge',
766 ... state_province='MA', country='U.S.A.',
767 ... website='http://www.oreilly.com/')
768 >>> publisher_list = Publisher.objects.all()
769 >>> publisher_list
770
771 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
772
773 Naturally, you can do quite a lot with the Django database API -- but first,
774 let's take care of a small annoyance.
775
776 Adding Model String Representations
777 ===================================
778
779 When we printed out the list of publishers, all we got was this
780 unhelpful display that makes it difficult to tell the ``Publisher`` objects
781 apart::
782
783 [<Publisher: Publisher object>, <Publisher: Publisher object>]
784
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
785 We can fix this easily by adding a method called ``__unicode__()`` to our
786 ``Publisher`` class. A ``__unicode__()`` method tells Python how to display the
787 "unicode" representation of an object. You can see this in action by adding a
788 ``__unicode__()`` method to the three models:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
789
790 .. parsed-literal::
791
792 from django.db import models
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
793
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
794 class Publisher(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
795 name = models.CharField(max_length=30)
796 address = models.CharField(max_length=50)
797 city = models.CharField(max_length=60)
798 state_province = models.CharField(max_length=30)
799 country = models.CharField(max_length=50)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
800 website = models.URLField()
801
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
802 **def __unicode__(self):**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
803 **return self.name**
804
805 class Author(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
806 first_name = models.CharField(max_length=30)
807 last_name = models.CharField(max_length=40)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
808 email = models.EmailField()
809
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
810 **def __unicode__(self):**
811 **return u'%s %s' % (self.first_name, self.last_name)**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
812
813 class Book(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
814 title = models.CharField(max_length=100)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
815 authors = models.ManyToManyField(Author)
816 publisher = models.ForeignKey(Publisher)
817 publication_date = models.DateField()
818
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
819 **def __unicode__(self):**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
820 **return self.title**
821
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
822 As you can see, a ``__unicode__()`` method can do whatever it needs to do in order
823 to return a representation of an object. Here, the ``__unicode__()`` methods for
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
824 ``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
825 respectively, but the ``__unicode__()`` for ``Author`` is slightly more complex --
826 it pieces together the ``first_name`` and ``last_name`` fields, separated by a
827 space.
828
829 The only requirement for ``__unicode__()`` is that it return a Unicode object.
830 If ``__unicode__()`` doesn't return a Unicode object -- if it returns, say, an
831 integer -- then Python will raise a ``TypeError`` with a message like
832 ``"coercing to Unicode: need string or buffer, int found"``.
833
834 .. admonition:: Unicode objects
835
836 What are Unicode objects?
837
838 You can think of a Unicode object as a Python string that can handle more
839 than a million different types of characters, from accented versions of
840 Latin characters to non-Latin characters to curly quotes and obscure
841 symbols.
842
843 Normal Python strings are *encoded*, which means they use an encoding such
844 as ASCII, ISO-8859-1 or UTF-8. If you're storing fancy characters (anything
845 beyond the standard 128 ASCII characters such as 0-9 and A-Z) in a normal
846 Python string, you have to keep track of which encoding your string is
847 using, or the fancy characters might appear messed up when they're
848 displayed or printed. Problems occur when you have data that's stored in
849 one encoding and you try to combine it with data in a different encoding,
850 or you try to display it in an application that assumes a certain encoding.
851 We've all seen Web pages and e-mails that are littered with "??? ??????"
852 or other characters in odd places; that generally suggests there's an
853 encoding problem.
854
855 Unicode objects, however, have no encoding; they use a consistent,
856 universal set of characters called, well, "Unicode." When you deal with
857 Unicode objects in Python, you can mix and match them safely without having
858 to worry about encoding issues.
859
860 Django uses Unicode objects throughout the framework. Model objects are
861 retrieved as Unicode objects, views interact with Unicode data, and
862 templates are rendered as Unicode. Generally, you won't have to worry about
863 making sure your encodings are right; things should just work.
864
865 Note that this has been a *very* high-level, dumbed down overview of
866 Unicode objects, and you owe it to yourself to learn more about the topic.
867 A good place to start is http://www.joelonsoftware.com/articles/Unicode.html .
868
869 For the ``__unicode__()`` changes to take effect, exit out of the Python shell
870 and enter it again with ``python manage.py shell``. (This is the simplest way
871 to make code changes take effect.) Now the list of ``Publisher`` objects is
872 much easier to understand::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
873
874 >>> from books.models import Publisher
875 >>> publisher_list = Publisher.objects.all()
876 >>> publisher_list
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
877 [<Publisher: Apress>, <Publisher: O'Reilly>]
878
879 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
880
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
881 Make sure any model you define has a ``__unicode__()`` method -- not only for
882 your own convenience when using the interactive interpreter, but also because
883 Django uses the output of ``__unicode__()`` in several places when it needs to
884 display objects.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
885
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
886 Finally, note that ``__unicode__()`` is a good example of adding *behavior* to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
887 models. A Django model describes more than the database table layout for an
888 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
889 ``__unicode__()`` is one example of such functionality -- a model knows how to
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
890 display itself.
891
892 Inserting and Updating Data
893 ===========================
894
895 You've already seen this done: to insert a row into your database, first create
896 an instance of your model using keyword arguments, like so::
897
898 >>> p = Publisher(name='Apress',
899 ... address='2855 Telegraph Ave.',
900 ... city='Berkeley',
901 ... state_province='CA',
902 ... country='U.S.A.',
903 ... website='http://www.apress.com/')
904
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
905 As we noted above, this act of instantiating a model class does *not* touch
906 the database. The record isn't saved into the database until you call
907 ``save()``, like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
908
909 >>> p.save()
910
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
911 .. SL Tested ok
912
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
913 In SQL, this can roughly be translated into the following::
914
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
915 INSERT INTO books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
916 (name, address, city, state_province, country, website)
917 VALUES
918 ('Apress', '2855 Telegraph Ave.', 'Berkeley', 'CA',
919 'U.S.A.', 'http://www.apress.com/');
920
921 Because the ``Publisher`` model uses an autoincrementing primary key ``id``,
922 the initial call to ``save()`` does one more thing: it calculates the primary
923 key value for the record and sets it to the ``id`` attribute on the instance::
924
925 >>> p.id
926 52 # this will differ based on your own data
927
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
928 .. SL Should be '52L' to match actual output.
929
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
930 Subsequent calls to ``save()`` will save the record in place, without creating
931 a new record (i.e., performing an SQL ``UPDATE`` statement instead of an
932 ``INSERT``)::
933
934 >>> p.name = 'Apress Publishing'
935 >>> p.save()
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
936
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
937 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
938
939 The preceding ``save()`` statement will result in roughly the following SQL::
940
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
941 UPDATE books_publisher SET
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
942 name = 'Apress Publishing',
943 address = '2855 Telegraph Ave.',
944 city = 'Berkeley',
945 state_province = 'CA',
946 country = 'U.S.A.',
947 website = 'http://www.apress.com'
948 WHERE id = 52;
949
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
950 Yes, note that *all* of the fields will be updated, not just the ones that have
951 been changed. Depending on your application, this may cause a race condition.
952 See "Updating Multiple Objects in One Statement" below to find out how to
953 execute this (slightly different) query::
954
955 UPDATE books_publisher SET
956 name = 'Apress Publishing'
957 WHERE id=52;
958
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
959 Selecting Objects
960 =================
961
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
962 Knowing how to create and update database records is essential, but chances are
963 that the Web applications you'll build will be doing more querying of existing
964 objects than creating new ones. We've already seen a way to retrieve *every*
965 record for a given model::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
966
967 >>> Publisher.objects.all()
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
968 [<Publisher: Apress>, <Publisher: O'Reilly>]
969
970 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
971
972 This roughly translates to this SQL::
973
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
974 SELECT id, name, address, city, state_province, country, website
975 FROM books_publisher;
976
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
977 .. note::
978
979 Notice that Django doesn't use ``SELECT *`` when looking up data and instead
980 lists all fields explicitly. This is by design: in certain circumstances
981 ``SELECT *`` can be slower, and (more important) listing fields more closely
982 follows one tenet of the Zen of Python: "Explicit is better than implicit."
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
983
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
984 For more on the Zen of Python, try typing ``import this`` at a Python
985 prompt.
986
987 Let's take a close look at each part of this ``Publisher.objects.all()`` line:
988
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
989 * First, we have the model we defined, ``Publisher``. No surprise here: when
990 you want to look up data, you use the model for that data.
991
992 * Next, we have the ``objects`` attribute. This is called a *manager*.
993 Managers are discussed in detail in Chapter 10. For now, all you need to
994 know is that managers take care of all "table-level" operations on data
995 including, most important, data lookup.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
996
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
997 All models automatically get a ``objects`` manager; you'll use it
998 any time you want to look up model instances.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
999
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1000 * Finally, we have ``all()``. This is a method on the ``objects`` manager
1001 that returns all the rows in the database. Though this object *looks*
1002 like a list, it's actually a *QuerySet* -- an object that represents a
1003 specific set of rows from the database. Appendix C deals with QuerySets
1004 in detail. For the rest of this chapter, we'll just treat them like the
1005 lists they emulate.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1006
1007 Any database lookup is going to follow this general pattern -- we'll call methods on
1008 the manager attached to the model we want to query against.
1009
1010 Filtering Data
1011 --------------
1012
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1013 Naturally, it's rare to want to select *everything* from a database at once; in
1014 most cases, you'll want to deal with a subset of your data. In the Django API,
1015 you can filter your data using the ``filter()`` method::
1016
1017 >>> Publisher.objects.filter(name='Apress')
1018 [<Publisher: Apress>]
1019
1020 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1021
1022 ``filter()`` takes keyword arguments that get translated into the appropriate
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1023 SQL ``WHERE`` clauses. The preceding example would get translated into
1024 something like this::
1025
1026 SELECT id, name, address, city, state_province, country, website
1027 FROM books_publisher
1028 WHERE name = 'Apress';
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1029
1030 You can pass multiple arguments into ``filter()`` to narrow down things further::
1031
1032 >>> Publisher.objects.filter(country="U.S.A.", state_province="CA")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1033 [<Publisher: Apress>]
1034
1035 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1036
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1037 Those multiple arguments get translated into SQL ``AND`` clauses. Thus, the
1038 example in the code snippet translates into the following::
1039
1040 SELECT id, name, address, city, state_province, country, website
1041 FROM books_publisher
1042 WHERE country = 'U.S.A.'
1043 AND state_province = 'CA';
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1044
1045 Notice that by default the lookups use the SQL ``=`` operator to do exact match
1046 lookups. Other lookup types are available::
1047
1048 >>> Publisher.objects.filter(name__contains="press")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1049 [<Publisher: Apress>]
1050
1051 .. SL Tested ok
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1052
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1053 That's a *double* underscore there between ``name`` and ``contains``. Like
1054 Python itself, Django uses the double underscore to signal that something
1055 "magic" is happening -- here, the ``__contains`` part gets translated by Django
1056 into a SQL ``LIKE`` statement::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1057
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1058 SELECT id, name, address, city, state_province, country, website
1059 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1060 WHERE name LIKE '%press%';
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1061
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1062 Many other types of lookups are available, including ``icontains``
1063 (case-insensitive ``LIKE``), ``startswith`` and ``endswith``, and ``range`` (SQL
1064 ``BETWEEN`` queries). Appendix C describes all of these lookup types in detail.
1065
1066 Retrieving Single Objects
1067 -------------------------
1068
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1069 The ``filter()`` examples above all returned a ``QuerySet``, which you can
1070 treat like a list. Sometimes it's more convenient to fetch only a single object,
1071 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
1072
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1073 >>> Publisher.objects.get(name="Apress")
1074 <Publisher: Apress>
1075
1076 .. SL Tested ok
1077
1078 Instead of a list (rather, ``QuerySet``), only a single object is returned.
1079 Because of that, a query resulting in multiple objects will cause an
1080 exception::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1081
1082 >>> Publisher.objects.get(country="U.S.A.")
1083 Traceback (most recent call last):
1084 ...
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1085 MultipleObjectsReturned: get() returned more than one Publisher --
1086 it returned 2! Lookup parameters were {'country': 'U.S.A.'}
1087
1088 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1089
1090 A query that returns no objects also causes an exception::
1091
1092 >>> Publisher.objects.get(name="Penguin")
1093 Traceback (most recent call last):
1094 ...
1095 DoesNotExist: Publisher matching query does not exist.
1096
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1097 .. SL Tested ok
1098
1099 The ``DoesNotExist`` exception is an attribute of the model's class --
1100 ``Publisher.DoesNotExist``. In your applications, you'll want to trap these
1101 exceptions, like this::
1102
1103 try:
1104 p = Publisher.objects.get(name='Apress')
1105 except Publisher.DoesNotExist:
1106 print "Apress isn't in the database yet."
1107 else:
1108 print "Apress is in the database."
1109
1110 .. SL Tested ok
1111
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1112 Ordering Data
1113 -------------
1114
1115 As you play around with the previous examples, you might discover that the objects
1116 are being returned in a seemingly random order. You aren't imagining things; so
1117 far we haven't told the database how to order its results, so we're simply
1118 getting back data in some arbitrary order chosen by the database.
1119
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1120 In your Django applications, you'll probably want to order your results
1121 according to a certain value -- say, alphabetically. To do this, use the
1122 ``order_by()`` method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1123
1124 >>> Publisher.objects.order_by("name")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1125 [<Publisher: Apress>, <Publisher: O'Reilly>]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1126
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1127 .. SL Tested ok
1128
1129 This doesn't look much different from the earlier ``all()`` example, but the
1130 SQL now includes a specific ordering::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1131
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1132 SELECT id, name, address, city, state_province, country, website
1133 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1134 ORDER BY name;
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1135
1136 You can order by any field you like::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1137
1138 >>> Publisher.objects.order_by("address")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1139 [<Publisher: O'Reilly>, <Publisher: Apress>]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1140
1141 >>> Publisher.objects.order_by("state_province")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1142 [<Publisher: Apress>, <Publisher: O'Reilly>]
1143
1144 .. SL Tested ok
1145
1146 To order by multiple fields (where the second field is used to disambiguate
1147 ordering in cases where the first is the same), use multiple arguments::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1148
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1149 >>> Publisher.objects.order_by("state_province", "address")
1150 [<Publisher: Apress>, <Publisher: O'Reilly>]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1151
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1152 .. SL Tested ok
1153
1154 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
1155 (that's a minus character)::
1156
1157 >>> Publisher.objects.order_by("-name")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1158 [<Publisher: O'Reilly>, <Publisher: Apress>]
1159
1160 .. SL Tested ok
1161
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1162 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
1163 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
1164 to order by. In these cases, Django lets you specify a default ordering in the
1165 model:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1166
1167 .. parsed-literal::
1168
1169 class Publisher(models.Model):
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1170 name = models.CharField(max_length=30)
1171 address = models.CharField(max_length=50)
1172 city = models.CharField(max_length=60)
1173 state_province = models.CharField(max_length=30)
1174 country = models.CharField(max_length=50)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1175 website = models.URLField()
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1176
1177 def __unicode__(self):
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1178 return self.name
1179
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1180 **class Meta:**
1181 **ordering = ['name']**
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1182
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1183 Here, we've introduced a new concept: the ``class Meta``, which is a class
1184 that's embedded within the ``Publisher`` class definition (i.e., it's indented
1185 to be within ``class Publisher``). You can use this ``Meta`` class on any model
1186 to specify various model-specific options. A full reference of ``Meta`` options
1187 is available in Appendix B, but for now, we're concerned with the ``ordering``
1188 option. If you specify this, it tells Django that unless an ordering is given
1189 explicitly with ``order_by()``, all ``Publisher`` objects should be ordered by
1190 the ``name`` field whenever they're retrieved with the Django database API.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1191
1192 Chaining Lookups
1193 ----------------
1194
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1195 You've seen how you can filter data, and you've seen how you can order it. Often, of course,
1196 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
1197
1198 >>> Publisher.objects.filter(country="U.S.A.").order_by("-name")
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1199 [<Publisher: O'Reilly>, <Publisher: Apress>]
1200
1201 .. SL Tested ok
1202
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1203 As you might expect, this translates to a SQL query with both a ``WHERE`` and an
1204 ``ORDER BY``::
1205
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1206 SELECT id, name, address, city, state_province, country, website
1207 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1208 WHERE country = 'U.S.A'
1209 ORDER BY name DESC;
1210
1211 Slicing Data
1212 ------------
1213
1214 Another common need is to look up only a fixed number of rows. Imagine you have thousands
1215 of publishers in your database, but you want to display only the first one. You can do this
1216 using Python's standard list slicing syntax::
1217
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1218 >>> Publisher.objects.order_by('name')[0]
1219 <Publisher: Apress>
1220
1221 .. SL Tested ok
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1222
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1223 This translates roughly to::
1224
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1225 SELECT id, name, address, city, state_province, country, website
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1226 FROM books_publisher
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1227 ORDER BY name
1228 LIMIT 1;
1229
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1230 Similarly, you can retrieve a specific subset of data using Python's
1231 range-slicing syntax::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1232
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1233 >>> Publisher.objects.order_by('name')[0:2]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1234
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1235 .. SL Tested ok (but should show expected output?)
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 This returns two objects, translating roughly to::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1238
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1239 SELECT id, name, address, city, state_province, country, website
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1240 FROM books_publisher
1241 ORDER BY name
1242 OFFSET 0 LIMIT 2;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1243
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1244 Note that negative slicing is *not* supported::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1245
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1246 >>> Publisher.objects.order_by('name')[-1]
1247 Traceback (most recent call last):
1248 ...
1249 AssertionError: Negative indexing is not supported.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1250
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1251 This is easy to get around, though. Just change the ``order_by()`` statement,
1252 like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1253
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1254 >>> Publisher.objects.order_by('-name')[0]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1255
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1256 Updating Multiple Objects in One Statement
1257 ------------------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1258
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1259 We pointed out in the "Inserting and Updating Data" section that the model
1260 ``save()`` method updates *all* columns in a row. Depending on your
1261 application, you may want to update only a subset of columns.
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 For example, let's say we want to update the Apress ``Publisher`` to change
1264 the name from ``'Apress'`` to ``'Apress Publishing'``. Using ``save()``, it
1265 would look something like this::
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 >>> p = Publisher.objects.get(name='Apress')
1268 >>> p.name = 'Apress Publishing'
1269 >>> p.save()
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
1270
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1271 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1272
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1273 This roughly translates to the following SQL::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1274
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1275 SELECT id, name, address, city, state_province, country, website
1276 FROM books_publisher
1277 WHERE name = 'Apress';
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 UPDATE books_publisher SET
1280 name = 'Apress Publishing',
1281 address = '2855 Telegraph Ave.',
1282 city = 'Berkeley',
1283 state_province = 'CA',
1284 country = 'U.S.A.',
1285 website = 'http://www.apress.com'
1286 WHERE id = 52;
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1287
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1288 (Note that this example assumes Apress has a publisher ID of ``52``.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1289
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1290 You can see in this example that Django's ``save()`` method sets *all* of the
1291 column values, not just the ``name`` column. If you're in an environment where
1292 other columns of the database might change due to some other process, it's
1293 smarter to change *only* the column you need to change. To do this, use the
1294 ``update()`` method on ``QuerySet`` objects. Here's an example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1295
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1296 >>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1297
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1298 .. SL Tested ok
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 The SQL translation here is much more efficient and has no chance of race
1301 conditions::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1302
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1303 UPDATE books_publisher
1304 SET name = 'Apress Publishing'
1305 WHERE id = 52;
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 The ``update()`` method works on any ``QuerySet``, which means you can edit
1308 multiple records in bulk. Here's how you might change the ``country`` from
1309 ``'U.S.A.'`` to ``USA`` in each ``Publisher`` record::
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 >>> Publisher.objects.all().update(country='USA')
1312 2
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1313
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1314 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1315
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1316 The ``update()`` method has a return value -- an integer representing how many
1317 records changed. In the above example, we got ``2``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1318
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1319 Deleting Objects
1320 ================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1321
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1322 To delete an object from your database, simply call the object's ``delete()``
1323 method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1324
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1325 >>> p = Publisher.objects.get(name="O'Reilly")
1326 >>> p.delete()
1327 >>> Publisher.objects.all()
1328 [<Publisher: Apress Publishing>]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1329
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1330 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1331
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1332 You can also delete objects in bulk by calling ``delete()`` on the result of
1333 any ``QuerySet``. This is similar to the ``update()`` method we showed in the
1334 last section::
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 >>> Publisher.objects.filter(country='USA').delete()
1337 >>> Publisher.objects.all().delete()
1338 >>> Publisher.objects.all()
1339 []
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1340
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1341 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1342
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1343 Be careful deleting your data! As a precaution against deleting all of the data
1344 in a particular table, Django requires you to explicitly use ``all()`` if you
1345 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
1346
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1347 >>> Publisher.objects.delete()
1348 Traceback (most recent call last):
1349 File "<console>", line 1, in <module>
1350 AttributeError: 'Manager' object has no attribute 'delete'
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1351
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1352 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1353
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1354 But it'll work if you add the ``all()`` method::
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 >>> Publisher.objects.all().delete()
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 .. SL Tested ok
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 If you're just deleting a subset of your data, you don't need to include
1361 ``all()``. To repeat a previous example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1362
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1363 >>> Publisher.objects.filter(country='USA').delete()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1364
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1365 .. SL Tested ok
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1366
1367 What's Next?
1368 ============
1369
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1370 Having read this chapter, you have enough knowledge of Django models to be able
1371 to write basic database applications. Chapter 10 will provide some information
1372 on more advanced usage of Django's database layer.
1373
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1374 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
1375 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
1376 advice about integrating with legacy databases. You might rely on site users
1377 to supply your data, in which case Chapter 7 will teach you how to process
1378 user-submitted form data.
1379
1380 But in some cases, you or your team might need to enter data manually, in which
1381 case it would be helpful to have a Web-based interface for entering and
ecb4057 @Funkmyster Ch5 - Fix link to Ch6
Funkmyster authored
1382 managing data. The :doc:`next chapter <chapter06>` covers Django's admin interface, which exists
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1383 precisely for that reason.
Something went wrong with that request. Please try again.