Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 1373 lines (973 sloc) 52.338 kB
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1 ==================================
2 Appendix B: Database API Reference
3 ==================================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
4
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
5 Django's database API is the other half of the model API discussed in Appendix
6 A. Once you've defined a model, you'll use this API any time you need to
7 access the database. You've seen examples of this API in use throughout the
8 book; this appendix explains all the various options in detail.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
9
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
10 Like the model APIs discussed in Appendix A, though these APIs are considered
11 very stable, the Django developers consistently add new shortcuts and
12 conveniences. It's a good idea to always check the latest documentation online,
13 available at http://docs.djangoproject.com/.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
14
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
15 Throughout this reference, we'll refer to the following models, which might form
16 a simple blog application::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
17
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
18 from django.db import models
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
19
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
20 class Blog(models.Model):
21 name = models.CharField(max_length=100)
22 tagline = models.TextField()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
23
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
24 def __unicode__(self):
25 return self.name
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
26
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
27 class Author(models.Model):
28 name = models.CharField(max_length=50)
29 email = models.EmailField()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
30
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
31 def __unicode__(self):
32 return self.name
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
33
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
34 class Entry(models.Model):
35 blog = models.ForeignKey(Blog)
36 headline = models.CharField(max_length=255)
37 body_text = models.TextField()
38 pub_date = models.DateTimeField()
39 authors = models.ManyToManyField(Author)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
40
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
41 def __unicode__(self):
42 return self.headline
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
43
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
44 Creating Objects
45 ================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
46
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
47 To create an object, instantiate it using keyword arguments to the model class, and
48 then call ``save()`` to save it to the database::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
49
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
50 >>> from mysite.blog.models import Blog
51 >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
52 >>> b.save()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
53
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
54 This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
55 the database until you explicitly call ``save()``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
56
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
57 The ``save()`` method has no return value.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
58
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
59 To create an object and save it all in one step, see the ``create`` manager
60 method.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
61
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
62 What Happens When You Save?
63 ---------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
64
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
65 When you save an object, Django performs the following steps:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
66
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
67 #. **Emit a pre_save signal.** This provides a notification that
68 an object is about to be saved. You can register a listener that
69 will be invoked whenever this signal is emitted. Check the online
70 documentation for more on signals.
71
72 #. **Preprocess the data.** Each field on the object is asked to
73 perform any automated data modification that the field may need
74 to perform.
75
76 Most fields do *no* preprocessing -- the field data is kept as is.
77 Preprocessing is only used on fields that have special behavior,
78 like file fields.
79
80 #. **Prepare the data for the database.** Each field is asked to provide
81 its current value in a data type that can be written to the database.
82
83 Most fields require no data preparation. Simple data types, such as
84 integers and strings, are "ready to write" as a Python object. However,
85 more complex data types often require some modification. For example,
86 ``DateFields`` use a Python ``datetime`` object to store data.
87 Databases don't store ``datetime`` objects, so the field value
88 must be converted into an ISO-compliant date string for insertion
89 into the database.
90
91 #. **Insert the data into the database.** The preprocessed, prepared
92 data is then composed into an SQL statement for insertion into the
93 database.
94
95 #. **Emit a post_save signal.** As with the ``pre_save`` signal, this
96 is used to provide notification that an object has been successfully
97 saved.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
98
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
99 Autoincrementing Primary Keys
100 ------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
101
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
102 For convenience, each model is given an autoincrementing primary key field
103 named ``id`` unless you explicitly specify ``primary_key=True`` on a field (see
104 the section titled "AutoField" in Appendix A).
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
105
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
106 If your model has an ``AutoField``, that autoincremented value will be
107 calculated and saved as an attribute on your object the first time you call
108 ``save()``::
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
109
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
110 >>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
111 >>> b2.id # Returns None, because b doesn't have an ID yet.
112 None
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
113
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
114 >>> b2.save()
115 >>> b2.id # Returns the ID of your new object.
116 14
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
117
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
118 There's no way to tell what the value of an ID will be before you call
119 ``save()``, because that value is calculated by your database, not by Django.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
120
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
121 If a model has an ``AutoField`` but you want to define a new object's ID
122 explicitly when saving, just define it explicitly before saving, rather than
123 relying on the autoassignment of the ID::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
124
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
125 >>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
126 >>> b3.id
127 3
128 >>> b3.save()
129 >>> b3.id
130 3
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
131
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
132 If you assign auto-primary-key values manually, make sure not to use an
133 already existing primary key value! If you create a new object with an explicit
134 primary key value that already exists in the database, Django will assume you're
135 changing the existing record rather than creating a new one.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
136
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
137 Given the preceding ``'Cheddar Talk'`` blog example, this example would override the
138 previous record in the database::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
139
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
140 >>> b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
141 >>> b4.save() # Overrides the previous blog with ID=3!
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
142
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
143 Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
144 objects, when you're confident you won't have primary key collision.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
145
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
146 Saving Changes to Objects
147 =========================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
148
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
149 To save changes to an object that's already in the database, use ``save()``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
150
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
151 Given a ``Blog`` instance ``b5`` that has already been saved to the database,
152 this example changes its name and updates its record in the database::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
153
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
154 >>> b5.name = 'New name'
155 >>> b5.save()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
156
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
157 This performs an ``UPDATE`` SQL statement behind the scenes. Again, Django
158 doesn't hit the database until you explicitly call ``save()``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
159
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
160 .. admonition:: How Django Knows When to ``UPDATE`` and When to ``INSERT``
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
161
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
162 You may have noticed that Django database objects use the same ``save()`` method
163 for creating and changing objects. Django abstracts the need to use
164 ``INSERT`` or ``UPDATE`` SQL statements. Specifically, when you call
165 ``save()``, Django follows this algorithm:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
166
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
167 * If the object's primary key attribute is set to a value that evaluates
168 to ``True`` (i.e., a value other than ``None`` or the empty string),
169 Django executes a ``SELECT`` query to determine whether a record with
170 the given primary key already exists.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
171
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
172 * If the record with the given primary key does already exist, Django
173 executes an ``UPDATE`` query.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
174
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
175 * If the object's primary key attribute is *not* set, or if it's set but
176 a record doesn't exist, Django executes an ``INSERT``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
177
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
178 Because of this, you should be careful not to specify a primary key value
179 explicitly when saving new objects if you cannot guarantee the primary key
180 value is unused.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
181
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
182 Updating ``ForeignKey`` fields works exactly the same way; simply assign an
183 object of the right type to the field in question::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
184
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
185 >>> joe = Author.objects.create(name="Joe")
186 >>> entry.author = joe
187 >>> entry.save()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
188
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
189 Django will complain if you try to assign an object of the wrong type.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
190
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
191 Retrieving Objects
192 ==================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
193
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
194 Throughout the book you've seen objects retrieved using code like the following::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
195
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
196 >>> blogs = Blog.objects.filter(author__name__contains="Joe")
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
197
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
198 There are quite a few "moving parts" behind the scenes here: when you
199 retrieve objects from the database, you're actually constructing a ``QuerySet``
200 using the model's ``Manager``. This ``QuerySet`` knows how to execute SQL and
201 return the requested objects.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
202
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
203 Appendix A looked at both of these objects from a model-definition point of
204 view; now we'll look at how they operate.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
205
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
206 A ``QuerySet`` represents a collection of objects from your database. It can
207 have zero, one, or many *filters* -- criteria that narrow down the collection
208 based on given parameters. In SQL terms, a ``QuerySet`` equates to a ``SELECT``
209 statement, and a filter is a ``WHERE``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
210
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
211 You get a ``QuerySet`` by using your model's ``Manager``. Each model has at
212 least one ``Manager``, and it's called ``objects`` by default. Access it
213 directly via the model class, like so::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
214
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
215 >>> Blog.objects
216 <django.db.models.manager.Manager object at 0x137d00d>
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
217
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
218 ``Manager``\s are accessible only via model classes, rather than from model
219 instances, to enforce a separation between "table-level" operations and
220 "record-level" operations::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
221
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
222 >>> b = Blog(name='Foo', tagline='Bar')
223 >>> b.objects
224 Traceback (most recent call last):
225 File "<stdin>", line 1, in <module>
226 AttributeError: Manager isn't accessible via Blog instances.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
227
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
228 The ``Manager`` is the main source of ``QuerySet``\s for a model. It acts as a
229 "root" ``QuerySet`` that describes all objects in the model's database table.
230 For example, ``Blog.objects`` is the initial ``QuerySet`` that contains all
231 ``Blog`` objects in the database.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
232
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
233 Caching and QuerySets
234 =====================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
235
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
236 Each ``QuerySet`` contains a cache, to minimize database access. It's important
237 to understand how it works, in order to write the most efficient code.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
238
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
239 In a newly created ``QuerySet``, the cache is empty. The first time a
240 ``QuerySet`` is evaluated -- and, hence, a database query happens -- Django
241 saves the query results in the ``QuerySet``'s cache and returns the results
242 that have been explicitly requested (e.g., the next element, if the
243 ``QuerySet`` is being iterated over). Subsequent evaluations of the
244 ``QuerySet`` reuse the cached results.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
245
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
246 Keep this caching behavior in mind, because it may bite you if you don't use
247 your ``QuerySet``\s correctly. For example, the following will create two
248 ``QuerySet``\s, evaluate them, and throw them away::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
249
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
250 print [e.headline for e in Entry.objects.all()]
251 print [e.pub_date for e in Entry.objects.all()]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
252
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
253 That means the same database query will be executed twice, effectively doubling
254 your database load. Also, there's a possibility the two lists may not include
255 the same database records, because an ``Entry`` may have been added or deleted
256 in the split second between the two requests.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
257
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
258 To avoid this problem, simply save the ``QuerySet`` and reuse it::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
259
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
260 queryset = Poll.objects.all()
261 print [p.headline for p in queryset] # Evaluate the query set.
262 print [p.pub_date for p in queryset] # Reuse the cache from the evaluation.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
263
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
264 Filtering Objects
265 =================
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 The simplest way to retrieve objects from a table is to get all of them.
268 To do this, use the ``all()`` method on a ``Manager``::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
269
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
270 >>> Entry.objects.all()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
271
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
272 The ``all()`` method returns a ``QuerySet`` of all the objects in the database.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
273
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
274 Usually, though, you'll need to select only a subset of the complete set of
275 objects. To create such a subset, you refine the initial ``QuerySet``, adding filter
276 conditions. You'll usually do this using the ``filter()`` and/or ``exclude()``
277 methods::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
278
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
279 >>> y2006 = Entry.objects.filter(pub_date__year=2006)
280 >>> not2006 = Entry.objects.exclude(pub_date__year=2006)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
281
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
282 ``filter()`` and ``exclude()`` both take *field lookup* arguments, which are
283 discussed in detail shortly.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
284
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
285 Chaining Filters
286 ----------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
287
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
288 The result of refining a ``QuerySet`` is itself a ``QuerySet``, so it's
289 possible to chain refinements together, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
290
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
291 >>> qs = Entry.objects.filter(headline__startswith='What')
292 >>> qs = qs.exclude(pub_date__gte=datetime.datetime.now())
293 >>> qs = qs.filter(pub_date__gte=datetime.datetime(2005, 1, 1))
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
294
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
295 This takes the initial ``QuerySet`` of all entries in the database, adds a
296 filter, then an exclusion, and then another filter. The final result is a
297 ``QuerySet`` containing all entries with a headline that starts with "What"
298 that were published between January 1, 2005, and the current day.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
299
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
300 It's important to point out here that ``QuerySets`` are lazy -- the act of creating
301 a ``QuerySet`` doesn't involve any database activity. In fact, the three preceding lines
302 don't make *any* database calls; you can chain filters together all day
303 long and Django won't actually run the query until the ``QuerySet`` is
304 *evaluated*.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
305
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
306 You can evaluate a ``QuerySet`` in any following ways:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
307
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
308 * *Iterating*: A ``QuerySet`` is iterable, and it executes its database query the first
309 time you iterate over it. For example, the following ``QuerySet`` isn't evaluated
310 until it's iterated over in the ``for`` loop::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
311
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
312 qs = Entry.objects.filter(pub_date__year=2006)
313 qs = qs.filter(headline__icontains="bill")
314 for e in qs:
315 print e.headline
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
316
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
317 This prints all headlines from 2006 that contain "bill" but causes
318 only one database hit.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
319
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
320 * *Printing it*: A ``QuerySet`` is evaluated when you call ``repr()`` on it.
321 This is for convenience in the Python interactive interpreter, so you can
322 immediately see your results when using the API interactively.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
323
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
324 * *Slicing*: As explained in the upcoming "Limiting QuerySets" section,
325 a ``QuerySet`` can be sliced using Python's array-slicing syntax.
326 Usually slicing a ``QuerySet`` returns another (unevaluated)``QuerySet``,
327 but Django will execute the database query if you use the "step"
328 parameter of slice syntax.
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 * *Converting to a list*: You can force evaluation of a ``QuerySet`` by calling
331 ``list()`` on it, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
332
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
333 >>> entry_list = list(Entry.objects.all())
334
335 Be warned, though, that this could have a large memory overhead, because
336 Django will load each element of the list into memory. In contrast,
337 iterating over a ``QuerySet`` will take advantage of your database to load
338 data and instantiate objects only as you need them.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
339
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
340 .. admonition:: Filtered QuerySets Are Unique
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
341
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
342 Each time you refine a ``QuerySet``, you get a brand-new ``QuerySet`` that
343 is in no way bound to the previous ``QuerySet``. Each refinement creates a
344 separate and distinct ``QuerySet`` that can be stored, used, and reused::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
345
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
346 q1 = Entry.objects.filter(headline__startswith="What")
347 q2 = q1.exclude(pub_date__gte=datetime.now())
348 q3 = q1.filter(pub_date__gte=datetime.now())
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
349
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
350 These three ``QuerySets`` are separate. The first is a base ``QuerySet``
351 containing all entries that contain a headline starting with "What". The
352 second is a subset of the first, with an additional criterion that excludes
353 records whose ``pub_date`` is greater than now. The third is a subset of the
354 first, with an additional criterion that selects only the records whose
355 ``pub_date`` is greater than now. The initial ``QuerySet`` (``q1``) is
356 unaffected by the refinement process.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
357
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
358 Limiting QuerySets
359 ------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
360
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
361 Use Python's array-slicing syntax to limit your ``QuerySet`` to a certain number
362 of results. This is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
363
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
364 For example, this returns the first five entries (``LIMIT 5``)::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
365
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
366 >>> Entry.objects.all()[:5]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
367
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
368 This returns the sixth through tenth entries (``OFFSET 5 LIMIT 5``)::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
369
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
370 >>> Entry.objects.all()[5:10]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
371
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
372 Generally, slicing a ``QuerySet`` returns a new ``QuerySet`` -- it doesn't
373 evaluate the query. An exception is if you use the "step" parameter
374 of Python slice syntax. For example, this would actually execute the query in
375 order to return a list of every *second* object of the first ten::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
376
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
377 >>> Entry.objects.all()[:10:2]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
378
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
379 To retrieve a *single* object rather than a list (e.g., ``SELECT foo FROM bar
380 LIMIT 1``), use a simple index instead of a slice. For example, this returns the
381 first ``Entry`` in the database, after ordering entries alphabetically by
382 headline::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
383
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
384 >>> Entry.objects.order_by('headline')[0]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
385
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
386 This is roughly equivalent to the following::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
387
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
388 >>> Entry.objects.order_by('headline')[0:1].get()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
389
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
390 Note, however, that the first of these will raise ``IndexError`` while the
391 second will raise ``DoesNotExist`` if no objects match the given criteria.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
392
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
393 Query Methods That Return New QuerySets
394 ---------------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
395
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
396 Django provides a range of ``QuerySet`` refinement methods that modify either
397 the types of results returned by the ``QuerySet`` or the way its SQL query is
398 executed. These methods are described in the sections that follow. Some of the
399 methods take field lookup arguments, which are discussed in detail a bit later
400 on.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
401
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
402 filter(\*\*lookup)
403 ~~~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
404
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
405 Returns a new ``QuerySet`` containing objects that match the given lookup
406 parameters.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
407
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
408 exclude(\*\*lookup)
409 ~~~~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
410
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
411 Returns a new ``QuerySet`` containing objects that do *not* match the given
412 lookup parameters.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
413
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
414 order_by(\*fields)
415 ~~~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
416
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
417 By default, results returned by a ``QuerySet`` are ordered by the ordering
418 tuple given by the ``ordering`` option in the model's metadata (see Appendix A). You can
419 override this for a particular query using the ``order_by()`` method::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
420
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
421 >> Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
422
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
423 This result will be ordered by ``pub_date`` descending, then by
424 ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
425 *descending* order. Ascending order is assumed if the ``-`` is absent. To order
426 randomly, use ``"?"``, like so::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
427
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
428 >>> Entry.objects.order_by('?')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
429
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
430 Ordering randomly incurs a performance penalty, though, so you shouldn't use it
431 for anything with heavy load.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
432
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
433 If no ordering is specified in a model's ``class Meta`` and a ``QuerySet`` from
434 that model doesn't include ``order_by()``, then ordering will be undefined and
435 may differ from query to query.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
436
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
437 distinct()
438 ~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
439
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
440 Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
441 eliminates duplicate rows from the query results.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
442
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
443 By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
444 is rarely a problem, because simple queries such as ``Blog.objects.all()`` don't
445 introduce the possibility of duplicate result rows.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
446
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
447 However, if your query spans multiple tables, it's possible to get duplicate
448 results when a ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
449
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
450 values(\*fields)
451 ~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
452
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
453 Returns a special ``QuerySet`` that evaluates to a list of dictionaries instead
454 of model-instance objects. Each of those dictionaries represents an object, with
455 the keys corresponding to the attribute names of model objects::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
456
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
457 # This list contains a Blog object.
458 >>> Blog.objects.filter(name__startswith='Beatles')
459 [Beatles Blog]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
460
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
461 # This list contains a dictionary.
462 >>> Blog.objects.filter(name__startswith='Beatles').values()
463 [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
464
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
465 ``values()`` takes optional positional arguments, ``*fields``, which specify
466 field names to which the ``SELECT`` should be limited. If you specify the
467 fields, each dictionary will contain only the field keys/values for the fields
468 you specify. If you don't specify the fields, each dictionary will contain a
469 key and value for every field in the database table::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
470
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
471 >>> Blog.objects.values()
472 [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
473 >>> Blog.objects.values('id', 'name')
474 [{'id': 1, 'name': 'Beatles Blog'}]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
475
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
476 This method is useful when you know you're only going to need values from a
477 small number of the available fields and you won't need the functionality of a
478 model instance object. It's more efficient to select only the fields you need to
479 use.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
480
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
481 dates(field, kind, order)
482 ~~~~~~~~~~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
483
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
484 Returns a special ``QuerySet`` that evaluates to a list of ``datetime.datetime``
485 objects representing all available dates of a particular kind within the
486 contents of the ``QuerySet``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
487
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
488 The ``field`` argument must be the name of a ``DateField`` or ``DateTimeField``
489 of your model. The ``kind`` argument must be either ``"year"``, ``"month"``, or
490 ``"day"``. Each ``datetime.datetime`` object in the result list is "truncated"
491 to the given ``type``:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
492
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
493 * ``"year"`` returns a list of all distinct year values for the field.
494
495 * ``"month"`` returns a list of all distinct year/month values for the field.
496
497 * ``"day"`` returns a list of all distinct year/month/day values for the field.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
498
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
499 ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
500 ``'DESC'``. This specifies how to order the results.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
501
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
502 Here are a few examples::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
503
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
504 >>> Entry.objects.dates('pub_date', 'year')
505 [datetime.datetime(2005, 1, 1)]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
506
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
507 >>> Entry.objects.dates('pub_date', 'month')
508 [datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
509
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
510 >>> Entry.objects.dates('pub_date', 'day')
511 [datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
512
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
513 >>> Entry.objects.dates('pub_date', 'day', order='DESC')
514 [datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
515
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
516 >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
517 [datetime.datetime(2005, 3, 20)]
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
518
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
519 select_related()
520 ~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
521
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
522 Returns a ``QuerySet`` that will automatically "follow" foreign key
523 relationships, selecting that additional related-object data when it executes
524 its query. This is a performance booster that results in (sometimes much)
525 larger queries but means later use of foreign key relationships won't require
526 database queries.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
527
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
528 The following examples illustrate the difference between plain lookups and
529 ``select_related()`` lookups. Here's standard lookup::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
530
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
531 # Hits the database.
532 >>> e = Entry.objects.get(id=5)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
533
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
534 # Hits the database again to get the related Blog object.
535 >>> b = e.blog
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
536
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
537 And here's ``select_related`` lookup::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
538
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
539 # Hits the database.
540 >>> e = Entry.objects.select_related().get(id=5)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
541
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
542 # Doesn't hit the database, because e.blog has been prepopulated
543 # in the previous query.
544 >>> b = e.blog
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
545
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
546 ``select_related()`` follows foreign keys as far as possible. If you have the
547 following models::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
548
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
549 class City(models.Model):
550 # ...
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
551
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
552 class Person(models.Model):
553 # ...
554 hometown = models.ForeignKey(City)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
555
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
556 class Book(models.Model):
557 # ...
558 author = models.ForeignKey(Person)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
559
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
560 then a call to ``Book.objects.select_related().get(id=4)`` will cache the
561 related ``Person`` *and* the related ``City``::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
562
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
563 >>> b = Book.objects.select_related().get(id=4)
564 >>> p = b.author # Doesn't hit the database.
565 >>> c = p.hometown # Doesn't hit the database.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
566
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
567 >>> b = Book.objects.get(id=4) # No select_related() in this example.
568 >>> p = b.author # Hits the database.
569 >>> c = p.hometown # Hits the database.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
570
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
571 Note that ``select_related()`` does not follow foreign keys that have
572 ``null=True``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
573
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
574 Usually, using ``select_related()`` can vastly improve performance because your
575 application can avoid many database calls. However, in situations with deeply nested
576 sets of relationships, ``select_related()`` can sometimes end up following "too
577 many" relations and can generate queries so large that they end up being slow.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
578
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
579 QuerySet Methods That Do Not Return QuerySets
580 ---------------------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
581
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
582 The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
583 something *other than* a ``QuerySet`` -- a single object, value, and so forth.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
584
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
585 get(\*\*lookup)
586 ~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
587
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
588 Returns the object matching the given lookup parameters, which should be in the
589 format described in the "Field Lookups" section. This raises ``AssertionError`` if
590 more than one object was found.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
591
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
592 ``get()`` raises a ``DoesNotExist`` exception if an object wasn't found for the
593 given parameters. The ``DoesNotExist`` exception is an attribute of the model
594 class, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
595
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
596 >>> Entry.objects.get(id='foo') # raises Entry.DoesNotExist
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
597
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
598 The ``DoesNotExist`` exception inherits from
599 ``django.core.exceptions.ObjectDoesNotExist``, so you can target multiple
600 ``DoesNotExist`` exceptions::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
601
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
602 >>> from django.core.exceptions import ObjectDoesNotExist
603 >>> try:
604 ... e = Entry.objects.get(id=3)
605 ... b = Blog.objects.get(id=1)
606 ... except ObjectDoesNotExist:
607 ... print "Either the entry or blog doesn't exist."
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
608
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
609 create(\*\*kwargs)
610 ~~~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
611
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
612 This is a convenience method for creating an object and saving it all in one step.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
613 It lets you compress two common steps::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
614
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
615 >>> p = Person(first_name="Bruce", last_name="Springsteen")
616 >>> p.save()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
617
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
618 into a single line::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
619
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
620 >>> p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
621
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
622 get_or_create(\*\*kwargs)
623 ~~~~~~~~~~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
624
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
625 This is a convenience method for looking up an object and creating one if it doesn't
626 exist. It returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
627 created object and ``created`` is a Boolean specifying whether a new object was
628 created.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
629
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
630 This method is meant as a shortcut to boilerplate code and is mostly useful for
631 data-import scripts. For example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
632
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
633 try:
634 obj = Person.objects.get(first_name='John', last_name='Lennon')
635 except Person.DoesNotExist:
636 obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
637 obj.save()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
638
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
639 This pattern gets quite unwieldy as the number of fields in a model increases. The
640 previous example can be rewritten using ``get_or_create()`` like so::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
641
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
642 obj, created = Person.objects.get_or_create(
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
643 first_name = 'John',
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
644 last_name = 'Lennon',
645 defaults = {'birthday': date(1940, 10, 9)}
646 )
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
647
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
648 Any keyword arguments passed to ``get_or_create()`` -- *except* an optional one
649 called ``defaults`` -- will be used in a ``get()`` call. If an object is found,
650 ``get_or_create()`` returns a tuple of that object and ``False``. If an object
651 is *not* found, ``get_or_create()`` will instantiate and save a new object,
652 returning a tuple of the new object and ``True``. The new object will be created
653 according to this algorithm::
654
655 defaults = kwargs.pop('defaults', {})
656 params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
657 params.update(defaults)
658 obj = self.model(**params)
659 obj.save()
660
661 In English, that means start with any non-``'defaults'`` keyword argument that
662 doesn't contain a double underscore (which would indicate a nonexact lookup).
663 Then add the contents of ``defaults``, overriding any keys if necessary, and
664 use the result as the keyword arguments to the model class.
665
666 If you have a field named ``defaults`` and want to use it as an exact lookup in
667 ``get_or_create()``, just use ``'defaults__exact'`` like so::
668
669 Foo.objects.get_or_create(
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
670 defaults__exact = 'bar',
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
671 defaults={'defaults': 'bar'}
672 )
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
673
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
674 .. note::
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
675
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
676 As mentioned earlier, ``get_or_create()`` is mostly useful in scripts that
677 need to parse data and create new records if existing ones aren't available.
678 But if you need to use ``get_or_create()`` in a view, please make sure to
679 use it only in ``POST`` requests unless you have a good reason not to.
680 ``GET`` requests shouldn't have any effect on data; use ``POST`` whenever a
681 request to a page has a side effect on your data.
682
683 count()
684 ~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
685
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
686 Returns an integer representing the number of objects in the database matching
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
687 the ``QuerySet``. ``count()`` never raises exceptions. Here's an example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
688
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
689 # Returns the total number of entries in the database.
690 >>> Entry.objects.count()
691 4
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
692
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
693 # Returns the number of entries whose headline contains 'Lennon'
694 >>> Entry.objects.filter(headline__contains='Lennon').count()
695 1
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
696
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
697 ``count()`` performs a ``SELECT COUNT(*)`` behind the scenes, so you should
698 always use ``count()`` rather than loading all of the records into Python objects
699 and calling ``len()`` on the result.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
700
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
701 Depending on which database you're using (e.g., PostgreSQL or MySQL),
702 ``count()`` may return a long integer instead of a normal Python integer. This
703 is an underlying implementation quirk that shouldn't pose any real-world
704 problems.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
705
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
706 in_bulk(id_list)
707 ~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
708
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
709 Takes a list of primary key values and returns a dictionary mapping each
710 primary key value to an instance of the object with the given ID, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
711
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
712 >>> Blog.objects.in_bulk([1])
713 {1: Beatles Blog}
714 >>> Blog.objects.in_bulk([1, 2])
715 {1: Beatles Blog, 2: Cheddar Talk}
716 >>> Blog.objects.in_bulk([])
717 {}
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
718
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
719 IDs of objects that don't exist are silently dropped from the result dictionary.
720 If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
721
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
722 latest(field_name=None)
723 ~~~~~~~~~~~~~~~~~~~~~~~
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
724
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
725 Returns the latest object in the table, by date, using the ``field_name``
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
726 provided as the date field. This example returns the latest ``Entry`` in the
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
727 table, according to the ``pub_date`` field::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
728
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
729 >>> Entry.objects.latest('pub_date')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
730
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
731 If your model's ``Meta`` specifies ``get_latest_by``, you can leave off the
732 ``field_name`` argument to ``latest()``. Django will use the field specified in
733 ``get_latest_by`` by default.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
734
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
735 Like ``get()``, ``latest()`` raises ``DoesNotExist`` if an object doesn't exist
736 with the given parameters.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
737
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
738 Field Lookups
739 =============
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
740
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
741 Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
742 specified as keyword arguments to the ``QuerySet`` methods ``filter()``,
743 ``exclude()``, and ``get()``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
744
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
745 Basic lookup keyword arguments take the form ``field__lookuptype=value``
746 (note the double underscore). For example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
747
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
748 >>> Entry.objects.filter(pub_date__lte='2006-01-01')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
749
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
750 translates (roughly) into the following SQL::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
751
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
752 SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
753
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
754 If you pass an invalid keyword argument, a lookup function will raise
755 ``TypeError``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
756
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
757 The supported lookup types follow.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
758
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
759 exact
760 -----
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
761
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
762 Performs an exact match::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
763
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
764 >>> Entry.objects.get(headline__exact="Man bites dog")
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
765
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
766 This matches any object with the exact headline "Man bites dog".
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
767
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
768 If you don't provide a lookup type -- that is, if your keyword argument doesn't
769 contain a double underscore -- the lookup type is assumed to be ``exact``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
770
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
771 For example, the following two statements are equivalent::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
772
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
773 >>> Blog.objects.get(id__exact=14) # Explicit form
774 >>> Blog.objects.get(id=14) # __exact is implied
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
775
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
776 This is for convenience, because ``exact`` lookups are the common case.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
777
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
778 iexact
779 ------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
780
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
781 Performs a case-insensitive exact match::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
782
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
783 >>> Blog.objects.get(name__iexact='beatles blog')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
784
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
785 This will match ``'Beatles Blog'``, ``'beatles blog'``,
786 ``'BeAtLes BLoG'``, and so forth.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
787
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
788 contains
789 --------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
790
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
791 Performs a case-sensitive containment test::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
792
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
793 Entry.objects.get(headline__contains='Lennon')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
794
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
795 This will match the headline ``'Today Lennon honored'`` but not
796 ``'today lennon honored'``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
797
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
798 SQLite doesn't support case-sensitive ``LIKE`` statements; when using
799 SQLite,``contains`` acts like ``icontains``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
800
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
801 .. admonition:: Escaping Percent Signs and Underscores in LIKE Statements
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
802
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
803 The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
804 ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``,
805 and ``iendswith``) will automatically escape the two special characters used in
806 ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
807 statement, the percent sign signifies a multiple-character wildcard and the
808 underscore signifies a single-character wildcard.)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
809
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
810 This means things should work intuitively, so the abstraction doesn't leak.
811 For example, to retrieve all the entries that contain a percent sign, just use
812 the percent sign as any other character::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
813
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
814 Entry.objects.filter(headline__contains='%')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
815
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
816 Django takes care of the quoting for you. The resulting SQL will look something
817 like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
818
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
819 SELECT ... WHERE headline LIKE '%\%%';
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
820
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
821 The same goes for underscores. Both percentage signs and underscores are handled
822 for you transparently.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
823
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
824 icontains
825 ---------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
826
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
827 Performs a case-insensitive containment test::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
828
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
829 >>> Entry.objects.get(headline__icontains='Lennon')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
830
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
831 Unlike ``contains``, ``icontains`` *will* match ``'today lennon honored'``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
832
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
833 gt, gte, lt, and lte
834 --------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
835
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
836 These represent greater than, greater than or equal to, less than, and less
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
837 than or equal to::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
838
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
839 >>> Entry.objects.filter(id__gt=4)
840 >>> Entry.objects.filter(id__lt=15)
841 >>> Entry.objects.filter(id__gte=0)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
842
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
843 These queries return any object with an ID greater than 4, an ID less than 15,
844 and an ID greater than or equal to 1, respectively.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
845
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
846 You'll usually use these on numeric fields. Be careful with character fields
847 since character order isn't always what you'd expect (i.e., the string "4" sorts
848 *after* the string "10").
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
849
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
850 in
851 --
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
852
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
853 Filters where a value is on a given list::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
854
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
855 Entry.objects.filter(id__in=[1, 3, 4])
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
856
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
857 This returns all objects with the ID 1, 3, or 4.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
858
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
859 startswith
860 ----------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
861
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
862 Performs a case-sensitive starts-with::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
863
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
864 >>> Entry.objects.filter(headline__startswith='Will')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
865
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
866 This will return the headlines "Will he run?" and "Willbur named judge", but not
867 "Who is Will?" or "will found in crypt".
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
868
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
869 istartswith
870 -----------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
871
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
872 Performs a case-insensitive starts-with::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
873
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
874 >>> Entry.objects.filter(headline__istartswith='will')
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
875
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
876 This will return the headlines "Will he run?", "Willbur named judge", and
877 "will found in crypt", but not "Who is Will?"
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
878
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
879 endswith and iendswith
880 ----------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
881
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
882 Perform case-sensitive and case-insensitive ends-with::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
883
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
884 >>> Entry.objects.filter(headline__endswith='cats')
885 >>> Entry.objects.filter(headline__iendswith='cats')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
886
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
887 Similar to ``startswith`` and ``istartswith``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
888
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
889 range
890 -----
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
891
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
892 Performs an inclusive range check::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
893
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
894 >>> start_date = datetime.date(2005, 1, 1)
895 >>> end_date = datetime.date(2005, 3, 31)
896 >>> Entry.objects.filter(pub_date__range=(start_date, end_date))
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
897
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
898 You can use ``range`` anywhere you can use ``BETWEEN`` in SQL -- for dates,
899 numbers, and even characters.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
900
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
901 year, month, and day
902 --------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
903
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
904 For date/datetime fields, perform exact year, month, or day matches::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
905
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
906 # Return all entries published in 2005
907 >>>Entry.objects.filter(pub_date__year=2005)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
908
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
909 # Return all entries published in December
910 >>> Entry.objects.filter(pub_date__month=12)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
911
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
912 # Return all entries published on the 3rd of the month
913 >>> Entry.objects.filter(pub_date__day=3)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
914
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
915 # Combination: return all entries on Christmas of any year
916 >>> Entry.objects.filter(pub_date__month=12, pub_date_day=25)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
917
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
918 isnull
919 ------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
920
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
921 Takes either ``True`` or ``False``, which correspond to SQL queries of
922 ``IS NULL`` and ``IS NOT NULL``, respectively::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
923
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
924 >>> Entry.objects.filter(pub_date__isnull=True)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
925
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
926 search
927 ------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
928
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
929 A Boolean full-text search that takes advantage of full-text indexing. This is like
930 ``contains`` but is significantly faster due to full-text indexing.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
931
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
932 Note this is available only in MySQL and requires direct manipulation of the
933 database to add the full-text index.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
934
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
935 The pk Lookup Shortcut
936 ----------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
937
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
938 For convenience, Django provides a ``pk`` lookup type, which stands for
939 "primary_key".
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
940
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
941 In the example ``Blog`` model, the primary key is the ``id`` field, so these
942 three statements are equivalent::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
943
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
944 >>> Blog.objects.get(id__exact=14) # Explicit form
945 >>> Blog.objects.get(id=14) # __exact is implied
946 >>> Blog.objects.get(pk=14) # pk implies id__exact
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
947
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
948 The use of ``pk`` isn't limited to ``__exact`` queries -- any query term can be
949 combined with ``pk`` to perform a query on the primary key of a model::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
950
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
951 # Get blogs entries with id 1, 4, and 7
952 >>> Blog.objects.filter(pk__in=[1,4,7])
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
953
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
954 # Get all blog entries with id > 14
955 >>> Blog.objects.filter(pk__gt=14)
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
956
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
957 ``pk`` lookups also work across joins. For example, these three statements are
958 equivalent::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
959
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
960 >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
961 >>> Entry.objects.filter(blog__id=3) # __exact is implied
962 >>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
963
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
964 The point of ``pk`` is to give you a generic way to refer to the primary key in
965 cases where you're not sure whether the model's primary key is called ``id``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
966
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
967 Complex Lookups with Q Objects
968 ==============================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
969
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
970 Keyword argument queries -- in ``filter()`` and so on -- are ANDed together. If
971 you need to execute more complex queries (e.g., queries with ``OR``
972 statements), you can use ``Q`` objects.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
973
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
974 A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a
975 collection of keyword arguments. These keyword arguments are specified as in
976 the "Field Lookups" section.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
977
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
978 For example, this ``Q`` object encapsulates a single ``LIKE`` query::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
979
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
980 Q(question__startswith='What')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
981
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
982 ``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
983 operator is used on two ``Q`` objects, it yields a new ``Q`` object. For example,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
984 this statement yields a single ``Q`` object that represents the
985 OR of two ``"question__startswith"`` queries::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
986
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
987 Q(question__startswith='Who') | Q(question__startswith='What')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
988
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
989 This is equivalent to the following SQL ``WHERE`` clause::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
990
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
991 WHERE question LIKE 'Who%' OR question LIKE 'What%'
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
992
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
993 You can compose statements of arbitrary complexity by combining ``Q`` objects
994 with the ``&`` and ``|`` operators. You can also use parenthetical grouping.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
995
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
996 Each lookup function that takes keyword arguments (e.g., ``filter()``,
997 ``exclude()``, ``get()``) can also be passed one or more ``Q`` objects as
998 positional (not-named) arguments. If you provide multiple ``Q`` object
999 arguments to a lookup function, the arguments will be ANDed together, for
1000 example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1001
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1002 Poll.objects.get(
1003 Q(question__startswith='Who'),
1004 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
1005 )
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1006
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1007 roughly translates into the following SQL::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1008
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1009 SELECT * from polls WHERE question LIKE 'Who%'
1010 AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1011
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1012 Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
1013 arguments provided to a lookup function (be they keyword arguments or ``Q``
1014 objects) are ANDed together. However, if a ``Q`` object is provided, it must
1015 precede the definition of any keyword arguments. For example, the following::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1016
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1017 Poll.objects.get(
1018 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
1019 question__startswith='Who')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1020
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1021 would be a valid query, equivalent to the previous example, but this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1022
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1023 # INVALID QUERY
1024 Poll.objects.get(
1025 question__startswith='Who',
1026 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1027
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1028 would not be valid.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1029
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1030 You can find some examples online at http://www.djangoproject.com/documentation/models/or_lookups/.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1031
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1032 Related Objects
1033 ===============
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1034
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1035 When you define a relationship in a model (i.e., a ``ForeignKey``,
1036 ``OneToOneField``, or ``ManyToManyField``), instances of that model will have
1037 a convenient API to access the related object(s).
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1038
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1039 For example, an ``Entry`` object ``e`` can get its associated ``Blog`` object by
1040 accessing the ``blog`` attribute ``e.blog``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1041
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1042 Django also creates API accessors for the "other" side of the relationship --
1043 the link from the related model to the model that defines the relationship.
1044 For example, a ``Blog`` object ``b`` has access to a list of all related
1045 ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1046
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1047 All examples in this section use the sample ``Blog``, ``Author``, and ``Entry``
1048 models defined at the start of the appendix.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1049
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1050 Lookups That Span Relationships
1051 -------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1052
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1053 Django offers a powerful and intuitive way to "follow" relationships in
1054 lookups, taking care of the SQL ``JOIN``\s for you automatically behind the
1055 scenes. To span a relationship, just use the field name of related fields
1056 across models, separated by double underscores, until you get to the field you
1057 want.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1058
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1059 This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
1060 is ``'Beatles Blog'``::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1061
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1062 >>> Entry.objects.filter(blog__name__exact='Beatles Blog')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1063
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1064 This spanning can be as deep as you'd like.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1065
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1066 It works backward, too. To refer to a "reverse" relationship, just use the
1067 lowercase name of the model.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1068
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1069 This example retrieves all ``Blog`` objects that have at least one ``Entry``
1070 whose ``headline`` contains ``'Lennon'``::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1071
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1072 >>> Blog.objects.filter(entry__headline__contains='Lennon')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1073
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1074 Foreign Key Relationships
1075 -------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1076
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1077 If a model has a ``ForeignKey``, instances of that model will have access to
1078 the related (foreign) object via a simple attribute of the model, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1079
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1080 e = Entry.objects.get(id=2)
1081 e.blog # Returns the related Blog object.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1082
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1083 You can get and set via a foreign key attribute. As you may expect, changes to
1084 the foreign key aren't saved to the database until you call ``save()``, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1085
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1086 e = Entry.objects.get(id=2)
1087 e.blog = some_blog
1088 e.save()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1089
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1090 If a ``ForeignKey`` field has ``null=True`` set (i.e., it allows ``NULL``
1091 values), you can set it to ``NULL`` by assigning ``None`` to it and saving::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1092
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1093 e = Entry.objects.get(id=2)
1094 e.blog = None
1095 e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1096
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1097 Forward access to one-to-many relationships is cached the first time the
1098 related object is accessed. Subsequent accesses to the foreign key on the same
1099 object instance are cached, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1100
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1101 e = Entry.objects.get(id=2)
1102 print e.blog # Hits the database to retrieve the associated Blog.
1103 print e.blog # Doesn't hit the database; uses cached version.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1104
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1105 Note that the ``select_related()`` ``QuerySet`` method recursively prepopulates
1106 the cache of all one-to-many relationships ahead of time::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1107
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1108 e = Entry.objects.select_related().get(id=2)
1109 print e.blog # Doesn't hit the database; uses cached version.
1110 print e.blog # Doesn't hit the database; uses cached version.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1111
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1112 ``select_related()`` is documented in the "QuerySet Methods That Return New
1113 QuerySets" section.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1114
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1115 "Reverse" Foreign Key Relationships
1116 -----------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1117
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1118 Foreign key relationships are automatically symmetrical -- a reverse
1119 relationship is inferred from the presence of a ``ForeignKey`` pointing to
1120 another model.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1121
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1122 If a model has a ``ForeignKey``, instances of the foreign key model will have
1123 access to a ``Manager`` that returns all instances of the first model that
1124 relate to that object. By default, this ``Manager`` is named ``FOO_set``, where
1125 ``FOO`` is the source model name, lowercased. This ``Manager`` returns
1126 ``QuerySets``, which can be filtered and manipulated as described in the
1127 "Retrieving Objects" section.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1128
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1129 Here's an example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1130
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1131 b = Blog.objects.get(id=1)
1132 b.entry_set.all() # Returns all Entry objects related to Blog.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1133
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1134 # b.entry_set is a Manager that returns QuerySets.
1135 b.entry_set.filter(headline__contains='Lennon')
1136 b.entry_set.count()
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1137
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1138 You can override the ``FOO_set`` name by setting the ``related_name``
1139 parameter in the ``ForeignKey()`` definition. For example, if the ``Entry``
1140 model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the
1141 preceding example code would look like this::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1142
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1143 b = Blog.objects.get(id=1)
1144 b.entries.all() # Returns all Entry objects related to Blog.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1145
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1146 # b.entries is a Manager that returns QuerySets.
1147 b.entries.filter(headline__contains='Lennon')