|
1 ============== |
|
2 Making queries |
|
3 ============== |
|
4 |
|
5 .. currentmodule:: django.db.models |
|
6 |
|
7 Once you've created your :doc:`data models </topics/db/models>`, Django |
|
8 automatically gives you a database-abstraction API that lets you create, |
|
9 retrieve, update and delete objects. This document explains how to use this |
|
10 API. Refer to the :doc:`data model reference </ref/models/index>` for full |
|
11 details of all the various model lookup options. |
|
12 |
|
13 Throughout this guide (and in the reference), we'll refer to the following |
|
14 models, which comprise a Weblog application: |
|
15 |
|
16 .. _queryset-model-example: |
|
17 |
|
18 .. code-block:: python |
|
19 |
|
20 class Blog(models.Model): |
|
21 name = models.CharField(max_length=100) |
|
22 tagline = models.TextField() |
|
23 |
|
24 def __unicode__(self): |
|
25 return self.name |
|
26 |
|
27 class Author(models.Model): |
|
28 name = models.CharField(max_length=50) |
|
29 email = models.EmailField() |
|
30 |
|
31 def __unicode__(self): |
|
32 return self.name |
|
33 |
|
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) |
|
40 n_comments = models.IntegerField() |
|
41 n_pingbacks = models.IntegerField() |
|
42 rating = models.IntegerField() |
|
43 |
|
44 def __unicode__(self): |
|
45 return self.headline |
|
46 |
|
47 Creating objects |
|
48 ================ |
|
49 |
|
50 To represent database-table data in Python objects, Django uses an intuitive |
|
51 system: A model class represents a database table, and an instance of that |
|
52 class represents a particular record in the database table. |
|
53 |
|
54 To create an object, instantiate it using keyword arguments to the model class, |
|
55 then call ``save()`` to save it to the database. |
|
56 |
|
57 You import the model class from wherever it lives on the Python path, as you |
|
58 may expect. (We point this out here because previous Django versions required |
|
59 funky model importing.) |
|
60 |
|
61 Assuming models live in a file ``mysite/blog/models.py``, here's an example:: |
|
62 |
|
63 >>> from blog.models import Blog |
|
64 >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') |
|
65 >>> b.save() |
|
66 |
|
67 This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit |
|
68 the database until you explicitly call ``save()``. |
|
69 |
|
70 The ``save()`` method has no return value. |
|
71 |
|
72 .. seealso:: |
|
73 |
|
74 ``save()`` takes a number of advanced options not described here. |
|
75 See the documentation for ``save()`` for complete details. |
|
76 |
|
77 To create an object and save it all in one step see the ```create()``` |
|
78 method. |
|
79 |
|
80 Saving changes to objects |
|
81 ========================= |
|
82 |
|
83 To save changes to an object that's already in the database, use ``save()``. |
|
84 |
|
85 Given a ``Blog`` instance ``b5`` that has already been saved to the database, |
|
86 this example changes its name and updates its record in the database:: |
|
87 |
|
88 >> b5.name = 'New name' |
|
89 >> b5.save() |
|
90 |
|
91 This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit |
|
92 the database until you explicitly call ``save()``. |
|
93 |
|
94 Saving ``ForeignKey`` and ``ManyToManyField`` fields |
|
95 ---------------------------------------------------- |
|
96 |
|
97 Updating a ``ForeignKey`` field works exactly the same way as saving a normal |
|
98 field; simply assign an object of the right type to the field in question. |
|
99 This example updates the ``blog`` attribute of an ``Entry`` instance ``entry``:: |
|
100 |
|
101 >>> from blog.models import Entry |
|
102 >>> entry = Entry.objects.get(pk=1) |
|
103 >>> cheese_blog = Blog.objects.get(name="Cheddar Talk") |
|
104 >>> entry.blog = cheese_blog |
|
105 >>> entry.save() |
|
106 |
|
107 Updating a ``ManyToManyField`` works a little differently; use the ``add()`` |
|
108 method on the field to add a record to the relation. This example adds the |
|
109 ``Author`` instance ``joe`` to the ``entry`` object:: |
|
110 |
|
111 >>> from blog.models import Author |
|
112 >>> joe = Author.objects.create(name="Joe") |
|
113 >>> entry.authors.add(joe) |
|
114 |
|
115 Django will complain if you try to assign or add an object of the wrong type. |
|
116 |
|
117 Retrieving objects |
|
118 ================== |
|
119 |
|
120 To retrieve objects from your database, you construct a ``QuerySet`` via a |
|
121 ``Manager`` on your model class. |
|
122 |
|
123 A ``QuerySet`` represents a collection of objects from your database. It can |
|
124 have zero, one or many *filters* -- criteria that narrow down the collection |
|
125 based on given parameters. In SQL terms, a ``QuerySet`` equates to a ``SELECT`` |
|
126 statement, and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``. |
|
127 |
|
128 You get a ``QuerySet`` by using your model's ``Manager``. Each model has at |
|
129 least one ``Manager``, and it's called ``objects`` by default. Access it |
|
130 directly via the model class, like so:: |
|
131 |
|
132 >>> Blog.objects |
|
133 <django.db.models.manager.Manager object at ...> |
|
134 >>> b = Blog(name='Foo', tagline='Bar') |
|
135 >>> b.objects |
|
136 Traceback: |
|
137 ... |
|
138 AttributeError: "Manager isn't accessible via Blog instances." |
|
139 |
|
140 .. note:: |
|
141 |
|
142 ``Managers`` are accessible only via model classes, rather than from model |
|
143 instances, to enforce a separation between "table-level" operations and |
|
144 "record-level" operations. |
|
145 |
|
146 The ``Manager`` is the main source of ``QuerySets`` for a model. It acts as a |
|
147 "root" ``QuerySet`` that describes all objects in the model's database table. |
|
148 For example, ``Blog.objects`` is the initial ``QuerySet`` that contains all |
|
149 ``Blog`` objects in the database. |
|
150 |
|
151 Retrieving all objects |
|
152 ---------------------- |
|
153 |
|
154 The simplest way to retrieve objects from a table is to get all of them. |
|
155 To do this, use the ``all()`` method on a ``Manager``:: |
|
156 |
|
157 >>> all_entries = Entry.objects.all() |
|
158 |
|
159 The ``all()`` method returns a ``QuerySet`` of all the objects in the database. |
|
160 |
|
161 (If ``Entry.objects`` is a ``QuerySet``, why can't we just do ``Entry.objects``? |
|
162 That's because ``Entry.objects``, the root ``QuerySet``, is a special case |
|
163 that cannot be evaluated. The ``all()`` method returns a ``QuerySet`` that |
|
164 *can* be evaluated.) |
|
165 |
|
166 |
|
167 Retrieving specific objects with filters |
|
168 ---------------------------------------- |
|
169 |
|
170 The root ``QuerySet`` provided by the ``Manager`` describes all objects in the |
|
171 database table. Usually, though, you'll need to select only a subset of the |
|
172 complete set of objects. |
|
173 |
|
174 To create such a subset, you refine the initial ``QuerySet``, adding filter |
|
175 conditions. The two most common ways to refine a ``QuerySet`` are: |
|
176 |
|
177 ``filter(**kwargs)`` |
|
178 Returns a new ``QuerySet`` containing objects that match the given |
|
179 lookup parameters. |
|
180 |
|
181 ``exclude(**kwargs)`` |
|
182 Returns a new ``QuerySet`` containing objects that do *not* match the |
|
183 given lookup parameters. |
|
184 |
|
185 The lookup parameters (``**kwargs`` in the above function definitions) should |
|
186 be in the format described in `Field lookups`_ below. |
|
187 |
|
188 For example, to get a ``QuerySet`` of blog entries from the year 2006, use |
|
189 ``filter()`` like so:: |
|
190 |
|
191 Entry.objects.filter(pub_date__year=2006) |
|
192 |
|
193 We don't have to add an ``all()`` -- ``Entry.objects.all().filter(...)``. That |
|
194 would still work, but you only need ``all()`` when you want all objects from the |
|
195 root ``QuerySet``. |
|
196 |
|
197 .. _chaining-filters: |
|
198 |
|
199 Chaining filters |
|
200 ~~~~~~~~~~~~~~~~ |
|
201 |
|
202 The result of refining a ``QuerySet`` is itself a ``QuerySet``, so it's |
|
203 possible to chain refinements together. For example:: |
|
204 |
|
205 >>> Entry.objects.filter( |
|
206 ... headline__startswith='What' |
|
207 ... ).exclude( |
|
208 ... pub_date__gte=datetime.now() |
|
209 ... ).filter( |
|
210 ... pub_date__gte=datetime(2005, 1, 1) |
|
211 ... ) |
|
212 |
|
213 This takes the initial ``QuerySet`` of all entries in the database, adds a |
|
214 filter, then an exclusion, then another filter. The final result is a |
|
215 ``QuerySet`` containing all entries with a headline that starts with "What", |
|
216 that were published between January 1, 2005, and the current day. |
|
217 |
|
218 .. _filtered-querysets-are-unique: |
|
219 |
|
220 Filtered QuerySets are unique |
|
221 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
222 |
|
223 Each time you refine a ``QuerySet``, you get a brand-new ``QuerySet`` that is |
|
224 in no way bound to the previous ``QuerySet``. Each refinement creates a |
|
225 separate and distinct ``QuerySet`` that can be stored, used and reused. |
|
226 |
|
227 Example:: |
|
228 |
|
229 >> q1 = Entry.objects.filter(headline__startswith="What") |
|
230 >> q2 = q1.exclude(pub_date__gte=datetime.now()) |
|
231 >> q3 = q1.filter(pub_date__gte=datetime.now()) |
|
232 |
|
233 These three ``QuerySets`` are separate. The first is a base ``QuerySet`` |
|
234 containing all entries that contain a headline starting with "What". The second |
|
235 is a subset of the first, with an additional criteria that excludes records |
|
236 whose ``pub_date`` is greater than now. The third is a subset of the first, |
|
237 with an additional criteria that selects only the records whose ``pub_date`` is |
|
238 greater than now. The initial ``QuerySet`` (``q1``) is unaffected by the |
|
239 refinement process. |
|
240 |
|
241 .. _querysets-are-lazy: |
|
242 |
|
243 QuerySets are lazy |
|
244 ~~~~~~~~~~~~~~~~~~ |
|
245 |
|
246 ``QuerySets`` are lazy -- the act of creating a ``QuerySet`` doesn't involve any |
|
247 database activity. You can stack filters together all day long, and Django won't |
|
248 actually run the query until the ``QuerySet`` is *evaluated*. Take a look at |
|
249 this example:: |
|
250 |
|
251 >>> q = Entry.objects.filter(headline__startswith="What") |
|
252 >>> q = q.filter(pub_date__lte=datetime.now()) |
|
253 >>> q = q.exclude(body_text__icontains="food") |
|
254 >>> print q |
|
255 |
|
256 Though this looks like three database hits, in fact it hits the database only |
|
257 once, at the last line (``print q``). In general, the results of a ``QuerySet`` |
|
258 aren't fetched from the database until you "ask" for them. When you do, the |
|
259 ``QuerySet`` is *evaluated* by accessing the database. For more details on |
|
260 exactly when evaluation takes place, see :ref:`when-querysets-are-evaluated`. |
|
261 |
|
262 |
|
263 .. _retrieving-single-object-with-get: |
|
264 |
|
265 Retrieving a single object with get |
|
266 ----------------------------------- |
|
267 |
|
268 ``.filter()`` will always give you a ``QuerySet``, even if only a single |
|
269 object matches the query - in this case, it will be a ``QuerySet`` containing |
|
270 a single element. |
|
271 |
|
272 If you know there is only one object that matches your query, you can use |
|
273 the ``get()`` method on a `Manager` which returns the object directly:: |
|
274 |
|
275 >>> one_entry = Entry.objects.get(pk=1) |
|
276 |
|
277 You can use any query expression with ``get()``, just like with ``filter()`` - |
|
278 again, see `Field lookups`_ below. |
|
279 |
|
280 Note that there is a difference between using ``.get()``, and using |
|
281 ``.filter()`` with a slice of ``[0]``. If there are no results that match the |
|
282 query, ``.get()`` will raise a ``DoesNotExist`` exception. This exception is an |
|
283 attribute of the model class that the query is being performed on - so in the |
|
284 code above, if there is no ``Entry`` object with a primary key of 1, Django will |
|
285 raise ``Entry.DoesNotExist``. |
|
286 |
|
287 Similarly, Django will complain if more than one item matches the ``get()`` |
|
288 query. In this case, it will raise ``MultipleObjectsReturned``, which again is |
|
289 an attribute of the model class itself. |
|
290 |
|
291 |
|
292 Other QuerySet methods |
|
293 ---------------------- |
|
294 |
|
295 Most of the time you'll use ``all()``, ``get()``, ``filter()`` and ``exclude()`` |
|
296 when you need to look up objects from the database. However, that's far from all |
|
297 there is; see the :ref:`QuerySet API Reference <queryset-api>` for a complete |
|
298 list of all the various ``QuerySet`` methods. |
|
299 |
|
300 .. _limiting-querysets: |
|
301 |
|
302 Limiting QuerySets |
|
303 ------------------ |
|
304 |
|
305 Use a subset of Python's array-slicing syntax to limit your ``QuerySet`` to a |
|
306 certain number of results. This is the equivalent of SQL's ``LIMIT`` and |
|
307 ``OFFSET`` clauses. |
|
308 |
|
309 For example, this returns the first 5 objects (``LIMIT 5``):: |
|
310 |
|
311 >>> Entry.objects.all()[:5] |
|
312 |
|
313 This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``):: |
|
314 |
|
315 >>> Entry.objects.all()[5:10] |
|
316 |
|
317 Negative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported. |
|
318 |
|
319 Generally, slicing a ``QuerySet`` returns a new ``QuerySet`` -- it doesn't |
|
320 evaluate the query. An exception is if you use the "step" parameter of Python |
|
321 slice syntax. For example, this would actually execute the query in order to |
|
322 return a list of every *second* object of the first 10:: |
|
323 |
|
324 >>> Entry.objects.all()[:10:2] |
|
325 |
|
326 To retrieve a *single* object rather than a list |
|
327 (e.g. ``SELECT foo FROM bar LIMIT 1``), use a simple index instead of a |
|
328 slice. For example, this returns the first ``Entry`` in the database, after |
|
329 ordering entries alphabetically by headline:: |
|
330 |
|
331 >>> Entry.objects.order_by('headline')[0] |
|
332 |
|
333 This is roughly equivalent to:: |
|
334 |
|
335 >>> Entry.objects.order_by('headline')[0:1].get() |
|
336 |
|
337 Note, however, that the first of these will raise ``IndexError`` while the |
|
338 second will raise ``DoesNotExist`` if no objects match the given criteria. See |
|
339 :meth:`~django.db.models.QuerySet.get` for more details. |
|
340 |
|
341 .. _field-lookups-intro: |
|
342 |
|
343 Field lookups |
|
344 ------------- |
|
345 |
|
346 Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're |
|
347 specified as keyword arguments to the ``QuerySet`` methods ``filter()``, |
|
348 ``exclude()`` and ``get()``. |
|
349 |
|
350 Basic lookups keyword arguments take the form ``field__lookuptype=value``. |
|
351 (That's a double-underscore). For example:: |
|
352 |
|
353 >>> Entry.objects.filter(pub_date__lte='2006-01-01') |
|
354 |
|
355 translates (roughly) into the following SQL:: |
|
356 |
|
357 SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01'; |
|
358 |
|
359 .. admonition:: How this is possible |
|
360 |
|
361 Python has the ability to define functions that accept arbitrary name-value |
|
362 arguments whose names and values are evaluated at runtime. For more |
|
363 information, see `Keyword Arguments`_ in the official Python tutorial. |
|
364 |
|
365 .. _`Keyword Arguments`: http://docs.python.org/tutorial/controlflow.html#keyword-arguments |
|
366 |
|
367 If you pass an invalid keyword argument, a lookup function will raise |
|
368 ``TypeError``. |
|
369 |
|
370 The database API supports about two dozen lookup types; a complete reference |
|
371 can be found in the :ref:`field lookup reference <field-lookups>`. To give you a taste of what's available, here's some of the more common lookups |
|
372 you'll probably use: |
|
373 |
|
374 :lookup:`exact` |
|
375 An "exact" match. For example:: |
|
376 |
|
377 >>> Entry.objects.get(headline__exact="Man bites dog") |
|
378 |
|
379 Would generate SQL along these lines: |
|
380 |
|
381 .. code-block:: sql |
|
382 |
|
383 SELECT ... WHERE headline = 'Man bites dog'; |
|
384 |
|
385 If you don't provide a lookup type -- that is, if your keyword argument |
|
386 doesn't contain a double underscore -- the lookup type is assumed to be |
|
387 ``exact``. |
|
388 |
|
389 For example, the following two statements are equivalent:: |
|
390 |
|
391 >>> Blog.objects.get(id__exact=14) # Explicit form |
|
392 >>> Blog.objects.get(id=14) # __exact is implied |
|
393 |
|
394 This is for convenience, because ``exact`` lookups are the common case. |
|
395 |
|
396 :lookup:`iexact` |
|
397 A case-insensitive match. So, the query:: |
|
398 |
|
399 >>> Blog.objects.get(name__iexact="beatles blog") |
|
400 |
|
401 Would match a ``Blog`` titled "Beatles Blog", "beatles blog", or even |
|
402 "BeAtlES blOG". |
|
403 |
|
404 :lookup:`contains` |
|
405 Case-sensitive containment test. For example:: |
|
406 |
|
407 Entry.objects.get(headline__contains='Lennon') |
|
408 |
|
409 Roughly translates to this SQL: |
|
410 |
|
411 .. code-block:: sql |
|
412 |
|
413 SELECT ... WHERE headline LIKE '%Lennon%'; |
|
414 |
|
415 Note this will match the headline ``'Today Lennon honored'`` but not |
|
416 ``'today lennon honored'``. |
|
417 |
|
418 There's also a case-insensitive version, :lookup:`icontains`. |
|
419 |
|
420 :lookup:`startswith`, :lookup:`endswith` |
|
421 Starts-with and ends-with search, respectively. There are also |
|
422 case-insensitive versions called :lookup:`istartswith` and |
|
423 :lookup:`iendswith`. |
|
424 |
|
425 Again, this only scratches the surface. A complete reference can be found in the |
|
426 :ref:`field lookup reference <field-lookups>`. |
|
427 |
|
428 Lookups that span relationships |
|
429 ------------------------------- |
|
430 |
|
431 Django offers a powerful and intuitive way to "follow" relationships in |
|
432 lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the |
|
433 scenes. To span a relationship, just use the field name of related fields |
|
434 across models, separated by double underscores, until you get to the field you |
|
435 want. |
|
436 |
|
437 This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name`` |
|
438 is ``'Beatles Blog'``:: |
|
439 |
|
440 >>> Entry.objects.filter(blog__name__exact='Beatles Blog') |
|
441 |
|
442 This spanning can be as deep as you'd like. |
|
443 |
|
444 It works backwards, too. To refer to a "reverse" relationship, just use the |
|
445 lowercase name of the model. |
|
446 |
|
447 This example retrieves all ``Blog`` objects which have at least one ``Entry`` |
|
448 whose ``headline`` contains ``'Lennon'``:: |
|
449 |
|
450 >>> Blog.objects.filter(entry__headline__contains='Lennon') |
|
451 |
|
452 If you are filtering across multiple relationships and one of the intermediate |
|
453 models doesn't have a value that meets the filter condition, Django will treat |
|
454 it as if there is an empty (all values are ``NULL``), but valid, object there. |
|
455 All this means is that no error will be raised. For example, in this filter:: |
|
456 |
|
457 Blog.objects.filter(entry__authors__name='Lennon') |
|
458 |
|
459 (if there was a related ``Author`` model), if there was no ``author`` |
|
460 associated with an entry, it would be treated as if there was also no ``name`` |
|
461 attached, rather than raising an error because of the missing ``author``. |
|
462 Usually this is exactly what you want to have happen. The only case where it |
|
463 might be confusing is if you are using ``isnull``. Thus:: |
|
464 |
|
465 Blog.objects.filter(entry__authors__name__isnull=True) |
|
466 |
|
467 will return ``Blog`` objects that have an empty ``name`` on the ``author`` and |
|
468 also those which have an empty ``author`` on the ``entry``. If you don't want |
|
469 those latter objects, you could write:: |
|
470 |
|
471 Blog.objects.filter(entry__authors__isnull=False, |
|
472 entry__authors__name__isnull=True) |
|
473 |
|
474 Spanning multi-valued relationships |
|
475 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
476 |
|
477 .. versionadded:: 1.0 |
|
478 |
|
479 When you are filtering an object based on a ``ManyToManyField`` or a reverse |
|
480 ``ForeignKey``, there are two different sorts of filter you may be |
|
481 interested in. Consider the ``Blog``/``Entry`` relationship (``Blog`` to |
|
482 ``Entry`` is a one-to-many relation). We might be interested in finding blogs |
|
483 that have an entry which has both *"Lennon"* in the headline and was published |
|
484 in 2008. Or we might want to find blogs that have an entry with *"Lennon"* in |
|
485 the headline as well as an entry that was published in 2008. Since there are |
|
486 multiple entries associated with a single ``Blog``, both of these queries are |
|
487 possible and make sense in some situations. |
|
488 |
|
489 The same type of situation arises with a ``ManyToManyField``. For example, if |
|
490 an ``Entry`` has a ``ManyToManyField`` called ``tags``, we might want to find |
|
491 entries linked to tags called *"music"* and *"bands"* or we might want an |
|
492 entry that contains a tag with a name of *"music"* and a status of *"public"*. |
|
493 |
|
494 To handle both of these situations, Django has a consistent way of processing |
|
495 ``filter()`` and ``exclude()`` calls. Everything inside a single ``filter()`` |
|
496 call is applied simultaneously to filter out items matching all those |
|
497 requirements. Successive ``filter()`` calls further restrict the set of |
|
498 objects, but for multi-valued relations, they apply to any object linked to |
|
499 the primary model, not necessarily those objects that were selected by an |
|
500 earlier ``filter()`` call. |
|
501 |
|
502 That may sound a bit confusing, so hopefully an example will clarify. To |
|
503 select all blogs that contain entries with both *"Lennon"* in the headline |
|
504 and that were published in 2008 (the same entry satisfying both conditions), |
|
505 we would write:: |
|
506 |
|
507 Blog.objects.filter(entry__headline__contains='Lennon', |
|
508 entry__pub_date__year=2008) |
|
509 |
|
510 To select all blogs that contain an entry with *"Lennon"* in the headline |
|
511 **as well as** an entry that was published in 2008, we would write:: |
|
512 |
|
513 Blog.objects.filter(entry__headline__contains='Lennon').filter( |
|
514 entry__pub_date__year=2008) |
|
515 |
|
516 In this second example, the first filter restricted the queryset to all those |
|
517 blogs linked to that particular type of entry. The second filter restricted |
|
518 the set of blogs *further* to those that are also linked to the second type of |
|
519 entry. The entries select by the second filter may or may not be the same as |
|
520 the entries in the first filter. We are filtering the ``Blog`` items with each |
|
521 filter statement, not the ``Entry`` items. |
|
522 |
|
523 All of this behavior also applies to ``exclude()``: all the conditions in a |
|
524 single ``exclude()`` statement apply to a single instance (if those conditions |
|
525 are talking about the same multi-valued relation). Conditions in subsequent |
|
526 ``filter()`` or ``exclude()`` calls that refer to the same relation may end up |
|
527 filtering on different linked objects. |
|
528 |
|
529 .. _query-expressions: |
|
530 |
|
531 Filters can reference fields on the model |
|
532 ----------------------------------------- |
|
533 |
|
534 .. versionadded:: 1.1 |
|
535 |
|
536 In the examples given so far, we have constructed filters that compare |
|
537 the value of a model field with a constant. But what if you want to compare |
|
538 the value of a model field with another field on the same model? |
|
539 |
|
540 Django provides the ``F()`` object to allow such comparisons. Instances |
|
541 of ``F()`` act as a reference to a model field within a query. These |
|
542 references can then be used in query filters to compare the values of two |
|
543 different fields on the same model instance. |
|
544 |
|
545 For example, to find a list of all blog entries that have had more comments |
|
546 than pingbacks, we construct an ``F()`` object to reference the comment count, |
|
547 and use that ``F()`` object in the query:: |
|
548 |
|
549 >>> from django.db.models import F |
|
550 >>> Entry.objects.filter(n_comments__gt=F('n_pingbacks')) |
|
551 |
|
552 Django supports the use of addition, subtraction, multiplication, |
|
553 division and modulo arithmetic with ``F()`` objects, both with constants |
|
554 and with other ``F()`` objects. To find all the blog entries with more than |
|
555 *twice* as many comments as pingbacks, we modify the query:: |
|
556 |
|
557 >>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2) |
|
558 |
|
559 To find all the entries where the rating of the entry is less than the |
|
560 sum of the pingback count and comment count, we would issue the |
|
561 query:: |
|
562 |
|
563 >>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks')) |
|
564 |
|
565 You can also use the double underscore notation to span relationships in |
|
566 an ``F()`` object. An ``F()`` object with a double underscore will introduce |
|
567 any joins needed to access the related object. For example, to retrieve all |
|
568 the entries where the author's name is the same as the blog name, we could |
|
569 issue the query: |
|
570 |
|
571 >>> Entry.objects.filter(authors__name=F('blog__name')) |
|
572 |
|
573 The pk lookup shortcut |
|
574 ---------------------- |
|
575 |
|
576 For convenience, Django provides a ``pk`` lookup shortcut, which stands for |
|
577 "primary key". |
|
578 |
|
579 In the example ``Blog`` model, the primary key is the ``id`` field, so these |
|
580 three statements are equivalent:: |
|
581 |
|
582 >>> Blog.objects.get(id__exact=14) # Explicit form |
|
583 >>> Blog.objects.get(id=14) # __exact is implied |
|
584 >>> Blog.objects.get(pk=14) # pk implies id__exact |
|
585 |
|
586 The use of ``pk`` isn't limited to ``__exact`` queries -- any query term |
|
587 can be combined with ``pk`` to perform a query on the primary key of a model:: |
|
588 |
|
589 # Get blogs entries with id 1, 4 and 7 |
|
590 >>> Blog.objects.filter(pk__in=[1,4,7]) |
|
591 |
|
592 # Get all blog entries with id > 14 |
|
593 >>> Blog.objects.filter(pk__gt=14) |
|
594 |
|
595 ``pk`` lookups also work across joins. For example, these three statements are |
|
596 equivalent:: |
|
597 |
|
598 >>> Entry.objects.filter(blog__id__exact=3) # Explicit form |
|
599 >>> Entry.objects.filter(blog__id=3) # __exact is implied |
|
600 >>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact |
|
601 |
|
602 Escaping percent signs and underscores in LIKE statements |
|
603 --------------------------------------------------------- |
|
604 |
|
605 The field lookups that equate to ``LIKE`` SQL statements (``iexact``, |
|
606 ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith`` |
|
607 and ``iendswith``) will automatically escape the two special characters used in |
|
608 ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE`` |
|
609 statement, the percent sign signifies a multiple-character wildcard and the |
|
610 underscore signifies a single-character wildcard.) |
|
611 |
|
612 This means things should work intuitively, so the abstraction doesn't leak. |
|
613 For example, to retrieve all the entries that contain a percent sign, just use |
|
614 the percent sign as any other character:: |
|
615 |
|
616 >>> Entry.objects.filter(headline__contains='%') |
|
617 |
|
618 Django takes care of the quoting for you; the resulting SQL will look something |
|
619 like this: |
|
620 |
|
621 .. code-block:: sql |
|
622 |
|
623 SELECT ... WHERE headline LIKE '%\%%'; |
|
624 |
|
625 Same goes for underscores. Both percentage signs and underscores are handled |
|
626 for you transparently. |
|
627 |
|
628 .. _caching-and-querysets: |
|
629 |
|
630 Caching and QuerySets |
|
631 --------------------- |
|
632 |
|
633 Each ``QuerySet`` contains a cache, to minimize database access. It's important |
|
634 to understand how it works, in order to write the most efficient code. |
|
635 |
|
636 In a newly created ``QuerySet``, the cache is empty. The first time a |
|
637 ``QuerySet`` is evaluated -- and, hence, a database query happens -- Django |
|
638 saves the query results in the ``QuerySet``'s cache and returns the results |
|
639 that have been explicitly requested (e.g., the next element, if the |
|
640 ``QuerySet`` is being iterated over). Subsequent evaluations of the |
|
641 ``QuerySet`` reuse the cached results. |
|
642 |
|
643 Keep this caching behavior in mind, because it may bite you if you don't use |
|
644 your ``QuerySet``\s correctly. For example, the following will create two |
|
645 ``QuerySet``\s, evaluate them, and throw them away:: |
|
646 |
|
647 >>> print [e.headline for e in Entry.objects.all()] |
|
648 >>> print [e.pub_date for e in Entry.objects.all()] |
|
649 |
|
650 That means the same database query will be executed twice, effectively doubling |
|
651 your database load. Also, there's a possibility the two lists may not include |
|
652 the same database records, because an ``Entry`` may have been added or deleted |
|
653 in the split second between the two requests. |
|
654 |
|
655 To avoid this problem, simply save the ``QuerySet`` and reuse it:: |
|
656 |
|
657 >>> queryset = Entry.objects.all() |
|
658 >>> print [p.headline for p in queryset] # Evaluate the query set. |
|
659 >>> print [p.pub_date for p in queryset] # Re-use the cache from the evaluation. |
|
660 |
|
661 .. _complex-lookups-with-q: |
|
662 |
|
663 Complex lookups with Q objects |
|
664 ============================== |
|
665 |
|
666 Keyword argument queries -- in ``filter()``, etc. -- are "AND"ed together. If |
|
667 you need to execute more complex queries (for example, queries with ``OR`` |
|
668 statements), you can use ``Q`` objects. |
|
669 |
|
670 A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a |
|
671 collection of keyword arguments. These keyword arguments are specified as in |
|
672 "Field lookups" above. |
|
673 |
|
674 For example, this ``Q`` object encapsulates a single ``LIKE`` query:: |
|
675 |
|
676 Q(question__startswith='What') |
|
677 |
|
678 ``Q`` objects can be combined using the ``&`` and ``|`` operators. When an |
|
679 operator is used on two ``Q`` objects, it yields a new ``Q`` object. |
|
680 |
|
681 For example, this statement yields a single ``Q`` object that represents the |
|
682 "OR" of two ``"question__startswith"`` queries:: |
|
683 |
|
684 Q(question__startswith='Who') | Q(question__startswith='What') |
|
685 |
|
686 This is equivalent to the following SQL ``WHERE`` clause:: |
|
687 |
|
688 WHERE question LIKE 'Who%' OR question LIKE 'What%' |
|
689 |
|
690 You can compose statements of arbitrary complexity by combining ``Q`` objects |
|
691 with the ``&`` and ``|`` operators and use parenthetical grouping. Also, ``Q`` |
|
692 objects can be negated using the ``~`` operator, allowing for combined lookups |
|
693 that combine both a normal query and a negated (``NOT``) query:: |
|
694 |
|
695 Q(question__startswith='Who') | ~Q(pub_date__year=2005) |
|
696 |
|
697 Each lookup function that takes keyword-arguments (e.g. ``filter()``, |
|
698 ``exclude()``, ``get()``) can also be passed one or more ``Q`` objects as |
|
699 positional (not-named) arguments. If you provide multiple ``Q`` object |
|
700 arguments to a lookup function, the arguments will be "AND"ed together. For |
|
701 example:: |
|
702 |
|
703 Poll.objects.get( |
|
704 Q(question__startswith='Who'), |
|
705 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) |
|
706 ) |
|
707 |
|
708 ... roughly translates into the SQL:: |
|
709 |
|
710 SELECT * from polls WHERE question LIKE 'Who%' |
|
711 AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06') |
|
712 |
|
713 Lookup functions can mix the use of ``Q`` objects and keyword arguments. All |
|
714 arguments provided to a lookup function (be they keyword arguments or ``Q`` |
|
715 objects) are "AND"ed together. However, if a ``Q`` object is provided, it must |
|
716 precede the definition of any keyword arguments. For example:: |
|
717 |
|
718 Poll.objects.get( |
|
719 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)), |
|
720 question__startswith='Who') |
|
721 |
|
722 ... would be a valid query, equivalent to the previous example; but:: |
|
723 |
|
724 # INVALID QUERY |
|
725 Poll.objects.get( |
|
726 question__startswith='Who', |
|
727 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))) |
|
728 |
|
729 ... would not be valid. |
|
730 |
|
731 .. seealso:: |
|
732 |
|
733 The `OR lookups examples`_ in the Django unit tests show some possible uses |
|
734 of ``Q``. |
|
735 |
|
736 .. _OR lookups examples: http://code.djangoproject.com/browser/django/trunk/tests/modeltests/or_lookups/tests.py |
|
737 |
|
738 Comparing objects |
|
739 ================= |
|
740 |
|
741 To compare two model instances, just use the standard Python comparison operator, |
|
742 the double equals sign: ``==``. Behind the scenes, that compares the primary |
|
743 key values of two models. |
|
744 |
|
745 Using the ``Entry`` example above, the following two statements are equivalent:: |
|
746 |
|
747 >>> some_entry == other_entry |
|
748 >>> some_entry.id == other_entry.id |
|
749 |
|
750 If a model's primary key isn't called ``id``, no problem. Comparisons will |
|
751 always use the primary key, whatever it's called. For example, if a model's |
|
752 primary key field is called ``name``, these two statements are equivalent:: |
|
753 |
|
754 >>> some_obj == other_obj |
|
755 >>> some_obj.name == other_obj.name |
|
756 |
|
757 .. _topics-db-queries-delete: |
|
758 |
|
759 Deleting objects |
|
760 ================ |
|
761 |
|
762 The delete method, conveniently, is named ``delete()``. This method immediately |
|
763 deletes the object and has no return value. Example:: |
|
764 |
|
765 e.delete() |
|
766 |
|
767 You can also delete objects in bulk. Every ``QuerySet`` has a ``delete()`` |
|
768 method, which deletes all members of that ``QuerySet``. |
|
769 |
|
770 For example, this deletes all ``Entry`` objects with a ``pub_date`` year of |
|
771 2005:: |
|
772 |
|
773 Entry.objects.filter(pub_date__year=2005).delete() |
|
774 |
|
775 Keep in mind that this will, whenever possible, be executed purely in |
|
776 SQL, and so the ``delete()`` methods of individual object instances |
|
777 will not necessarily be called during the process. If you've provided |
|
778 a custom ``delete()`` method on a model class and want to ensure that |
|
779 it is called, you will need to "manually" delete instances of that |
|
780 model (e.g., by iterating over a ``QuerySet`` and calling ``delete()`` |
|
781 on each object individually) rather than using the bulk ``delete()`` |
|
782 method of a ``QuerySet``. |
|
783 |
|
784 When Django deletes an object, it emulates the behavior of the SQL |
|
785 constraint ``ON DELETE CASCADE`` -- in other words, any objects which |
|
786 had foreign keys pointing at the object to be deleted will be deleted |
|
787 along with it. For example:: |
|
788 |
|
789 b = Blog.objects.get(pk=1) |
|
790 # This will delete the Blog and all of its Entry objects. |
|
791 b.delete() |
|
792 |
|
793 Note that ``delete()`` is the only ``QuerySet`` method that is not exposed on a |
|
794 ``Manager`` itself. This is a safety mechanism to prevent you from accidentally |
|
795 requesting ``Entry.objects.delete()``, and deleting *all* the entries. If you |
|
796 *do* want to delete all the objects, then you have to explicitly request a |
|
797 complete query set:: |
|
798 |
|
799 Entry.objects.all().delete() |
|
800 |
|
801 .. _topics-db-queries-update: |
|
802 |
|
803 Updating multiple objects at once |
|
804 ================================= |
|
805 |
|
806 .. versionadded:: 1.0 |
|
807 |
|
808 Sometimes you want to set a field to a particular value for all the objects in |
|
809 a ``QuerySet``. You can do this with the ``update()`` method. For example:: |
|
810 |
|
811 # Update all the headlines with pub_date in 2007. |
|
812 Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same') |
|
813 |
|
814 You can only set non-relation fields and ``ForeignKey`` fields using this |
|
815 method. To update a non-relation field, provide the new value as a constant. |
|
816 To update ``ForeignKey`` fields, set the new value to be the new model |
|
817 instance you want to point to. For example:: |
|
818 |
|
819 >>> b = Blog.objects.get(pk=1) |
|
820 |
|
821 # Change every Entry so that it belongs to this Blog. |
|
822 >>> Entry.objects.all().update(blog=b) |
|
823 |
|
824 The ``update()`` method is applied instantly and returns the number of rows |
|
825 affected by the query. The only restriction on the ``QuerySet`` that is |
|
826 updated is that it can only access one database table, the model's main |
|
827 table. You can filter based on related fields, but you can only update columns |
|
828 in the model's main table. Example:: |
|
829 |
|
830 >>> b = Blog.objects.get(pk=1) |
|
831 |
|
832 # Update all the headlines belonging to this Blog. |
|
833 >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same') |
|
834 |
|
835 Be aware that the ``update()`` method is converted directly to an SQL |
|
836 statement. It is a bulk operation for direct updates. It doesn't run any |
|
837 ``save()`` methods on your models, or emit the ``pre_save`` or ``post_save`` |
|
838 signals (which are a consequence of calling ``save()``). If you want to save |
|
839 every item in a ``QuerySet`` and make sure that the ``save()`` method is |
|
840 called on each instance, you don't need any special function to handle that. |
|
841 Just loop over them and call ``save()``:: |
|
842 |
|
843 for item in my_queryset: |
|
844 item.save() |
|
845 |
|
846 .. versionadded:: 1.1 |
|
847 |
|
848 Calls to update can also use :ref:`F() objects <query-expressions>` to update |
|
849 one field based on the value of another field in the model. This is especially |
|
850 useful for incrementing counters based upon their current value. For example, to |
|
851 increment the pingback count for every entry in the blog:: |
|
852 |
|
853 >>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1) |
|
854 |
|
855 However, unlike ``F()`` objects in filter and exclude clauses, you can't |
|
856 introduce joins when you use ``F()`` objects in an update -- you can only |
|
857 reference fields local to the model being updated. If you attempt to introduce |
|
858 a join with an ``F()`` object, a ``FieldError`` will be raised:: |
|
859 |
|
860 # THIS WILL RAISE A FieldError |
|
861 >>> Entry.objects.update(headline=F('blog__name')) |
|
862 |
|
863 Related objects |
|
864 =============== |
|
865 |
|
866 When you define a relationship in a model (i.e., a ``ForeignKey``, |
|
867 ``OneToOneField``, or ``ManyToManyField``), instances of that model will have |
|
868 a convenient API to access the related object(s). |
|
869 |
|
870 Using the models at the top of this page, for example, an ``Entry`` object ``e`` |
|
871 can get its associated ``Blog`` object by accessing the ``blog`` attribute: |
|
872 ``e.blog``. |
|
873 |
|
874 (Behind the scenes, this functionality is implemented by Python descriptors_. |
|
875 This shouldn't really matter to you, but we point it out here for the curious.) |
|
876 |
|
877 Django also creates API accessors for the "other" side of the relationship -- |
|
878 the link from the related model to the model that defines the relationship. |
|
879 For example, a ``Blog`` object ``b`` has access to a list of all related |
|
880 ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``. |
|
881 |
|
882 All examples in this section use the sample ``Blog``, ``Author`` and ``Entry`` |
|
883 models defined at the top of this page. |
|
884 |
|
885 .. _descriptors: http://users.rcn.com/python/download/Descriptor.htm |
|
886 |
|
887 One-to-many relationships |
|
888 ------------------------- |
|
889 |
|
890 Forward |
|
891 ~~~~~~~ |
|
892 |
|
893 If a model has a ``ForeignKey``, instances of that model will have access to |
|
894 the related (foreign) object via a simple attribute of the model. |
|
895 |
|
896 Example:: |
|
897 |
|
898 >>> e = Entry.objects.get(id=2) |
|
899 >>> e.blog # Returns the related Blog object. |
|
900 |
|
901 You can get and set via a foreign-key attribute. As you may expect, changes to |
|
902 the foreign key aren't saved to the database until you call ``save()``. |
|
903 Example:: |
|
904 |
|
905 >>> e = Entry.objects.get(id=2) |
|
906 >>> e.blog = some_blog |
|
907 >>> e.save() |
|
908 |
|
909 If a ``ForeignKey`` field has ``null=True`` set (i.e., it allows ``NULL`` |
|
910 values), you can assign ``None`` to it. Example:: |
|
911 |
|
912 >>> e = Entry.objects.get(id=2) |
|
913 >>> e.blog = None |
|
914 >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;" |
|
915 |
|
916 Forward access to one-to-many relationships is cached the first time the |
|
917 related object is accessed. Subsequent accesses to the foreign key on the same |
|
918 object instance are cached. Example:: |
|
919 |
|
920 >>> e = Entry.objects.get(id=2) |
|
921 >>> print e.blog # Hits the database to retrieve the associated Blog. |
|
922 >>> print e.blog # Doesn't hit the database; uses cached version. |
|
923 |
|
924 Note that the ``select_related()`` ``QuerySet`` method recursively prepopulates |
|
925 the cache of all one-to-many relationships ahead of time. Example:: |
|
926 |
|
927 >>> e = Entry.objects.select_related().get(id=2) |
|
928 >>> print e.blog # Doesn't hit the database; uses cached version. |
|
929 >>> print e.blog # Doesn't hit the database; uses cached version. |
|
930 |
|
931 .. _backwards-related-objects: |
|
932 |
|
933 Following relationships "backward" |
|
934 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
935 |
|
936 If a model has a ``ForeignKey``, instances of the foreign-key model will have |
|
937 access to a ``Manager`` that returns all instances of the first model. By |
|
938 default, this ``Manager`` is named ``FOO_set``, where ``FOO`` is the source |
|
939 model name, lowercased. This ``Manager`` returns ``QuerySets``, which can be |
|
940 filtered and manipulated as described in the "Retrieving objects" section |
|
941 above. |
|
942 |
|
943 Example:: |
|
944 |
|
945 >>> b = Blog.objects.get(id=1) |
|
946 >>> b.entry_set.all() # Returns all Entry objects related to Blog. |
|
947 |
|
948 # b.entry_set is a Manager that returns QuerySets. |
|
949 >>> b.entry_set.filter(headline__contains='Lennon') |
|
950 >>> b.entry_set.count() |
|
951 |
|
952 You can override the ``FOO_set`` name by setting the ``related_name`` |
|
953 parameter in the ``ForeignKey()`` definition. For example, if the ``Entry`` |
|
954 model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the |
|
955 above example code would look like this:: |
|
956 |
|
957 >>> b = Blog.objects.get(id=1) |
|
958 >>> b.entries.all() # Returns all Entry objects related to Blog. |
|
959 |
|
960 # b.entries is a Manager that returns QuerySets. |
|
961 >>> b.entries.filter(headline__contains='Lennon') |
|
962 >>> b.entries.count() |
|
963 |
|
964 You cannot access a reverse ``ForeignKey`` ``Manager`` from the class; it must |
|
965 be accessed from an instance:: |
|
966 |
|
967 >>> Blog.entry_set |
|
968 Traceback: |
|
969 ... |
|
970 AttributeError: "Manager must be accessed via instance". |
|
971 |
|
972 In addition to the ``QuerySet`` methods defined in "Retrieving objects" above, |
|
973 the ``ForeignKey`` ``Manager`` has additional methods used to handle the set of |
|
974 related objects. A synopsis of each is below, and complete details can be found |
|
975 in the :doc:`related objects reference </ref/models/relations>`. |
|
976 |
|
977 ``add(obj1, obj2, ...)`` |
|
978 Adds the specified model objects to the related object set. |
|
979 |
|
980 ``create(**kwargs)`` |
|
981 Creates a new object, saves it and puts it in the related object set. |
|
982 Returns the newly created object. |
|
983 |
|
984 ``remove(obj1, obj2, ...)`` |
|
985 Removes the specified model objects from the related object set. |
|
986 |
|
987 ``clear()`` |
|
988 Removes all objects from the related object set. |
|
989 |
|
990 To assign the members of a related set in one fell swoop, just assign to it |
|
991 from any iterable object. The iterable can contain object instances, or just |
|
992 a list of primary key values. For example:: |
|
993 |
|
994 b = Blog.objects.get(id=1) |
|
995 b.entry_set = [e1, e2] |
|
996 |
|
997 In this example, ``e1`` and ``e2`` can be full Entry instances, or integer |
|
998 primary key values. |
|
999 |
|
1000 If the ``clear()`` method is available, any pre-existing objects will be |
|
1001 removed from the ``entry_set`` before all objects in the iterable (in this |
|
1002 case, a list) are added to the set. If the ``clear()`` method is *not* |
|
1003 available, all objects in the iterable will be added without removing any |
|
1004 existing elements. |
|
1005 |
|
1006 Each "reverse" operation described in this section has an immediate effect on |
|
1007 the database. Every addition, creation and deletion is immediately and |
|
1008 automatically saved to the database. |
|
1009 |
|
1010 Many-to-many relationships |
|
1011 -------------------------- |
|
1012 |
|
1013 Both ends of a many-to-many relationship get automatic API access to the other |
|
1014 end. The API works just as a "backward" one-to-many relationship, above. |
|
1015 |
|
1016 The only difference is in the attribute naming: The model that defines the |
|
1017 ``ManyToManyField`` uses the attribute name of that field itself, whereas the |
|
1018 "reverse" model uses the lowercased model name of the original model, plus |
|
1019 ``'_set'`` (just like reverse one-to-many relationships). |
|
1020 |
|
1021 An example makes this easier to understand:: |
|
1022 |
|
1023 e = Entry.objects.get(id=3) |
|
1024 e.authors.all() # Returns all Author objects for this Entry. |
|
1025 e.authors.count() |
|
1026 e.authors.filter(name__contains='John') |
|
1027 |
|
1028 a = Author.objects.get(id=5) |
|
1029 a.entry_set.all() # Returns all Entry objects for this Author. |
|
1030 |
|
1031 Like ``ForeignKey``, ``ManyToManyField`` can specify ``related_name``. In the |
|
1032 above example, if the ``ManyToManyField`` in ``Entry`` had specified |
|
1033 ``related_name='entries'``, then each ``Author`` instance would have an |
|
1034 ``entries`` attribute instead of ``entry_set``. |
|
1035 |
|
1036 One-to-one relationships |
|
1037 ------------------------ |
|
1038 |
|
1039 One-to-one relationships are very similar to many-to-one relationships. If you |
|
1040 define a :class:`~django.db.models.OneToOneField` on your model, instances of |
|
1041 that model will have access to the related object via a simple attribute of the |
|
1042 model. |
|
1043 |
|
1044 For example:: |
|
1045 |
|
1046 class EntryDetail(models.Model): |
|
1047 entry = models.OneToOneField(Entry) |
|
1048 details = models.TextField() |
|
1049 |
|
1050 ed = EntryDetail.objects.get(id=2) |
|
1051 ed.entry # Returns the related Entry object. |
|
1052 |
|
1053 The difference comes in "reverse" queries. The related model in a one-to-one |
|
1054 relationship also has access to a :class:`~django.db.models.Manager` object, but |
|
1055 that :class:`~django.db.models.Manager` represents a single object, rather than |
|
1056 a collection of objects:: |
|
1057 |
|
1058 e = Entry.objects.get(id=2) |
|
1059 e.entrydetail # returns the related EntryDetail object |
|
1060 |
|
1061 If no object has been assigned to this relationship, Django will raise |
|
1062 a ``DoesNotExist`` exception. |
|
1063 |
|
1064 Instances can be assigned to the reverse relationship in the same way as |
|
1065 you would assign the forward relationship:: |
|
1066 |
|
1067 e.entrydetail = ed |
|
1068 |
|
1069 How are the backward relationships possible? |
|
1070 -------------------------------------------- |
|
1071 |
|
1072 Other object-relational mappers require you to define relationships on both |
|
1073 sides. The Django developers believe this is a violation of the DRY (Don't |
|
1074 Repeat Yourself) principle, so Django only requires you to define the |
|
1075 relationship on one end. |
|
1076 |
|
1077 But how is this possible, given that a model class doesn't know which other |
|
1078 model classes are related to it until those other model classes are loaded? |
|
1079 |
|
1080 The answer lies in the :setting:`INSTALLED_APPS` setting. The first time any model is |
|
1081 loaded, Django iterates over every model in :setting:`INSTALLED_APPS` and creates the |
|
1082 backward relationships in memory as needed. Essentially, one of the functions |
|
1083 of :setting:`INSTALLED_APPS` is to tell Django the entire model domain. |
|
1084 |
|
1085 Queries over related objects |
|
1086 ---------------------------- |
|
1087 |
|
1088 Queries involving related objects follow the same rules as queries involving |
|
1089 normal value fields. When specifying the value for a query to match, you may |
|
1090 use either an object instance itself, or the primary key value for the object. |
|
1091 |
|
1092 For example, if you have a Blog object ``b`` with ``id=5``, the following |
|
1093 three queries would be identical:: |
|
1094 |
|
1095 Entry.objects.filter(blog=b) # Query using object instance |
|
1096 Entry.objects.filter(blog=b.id) # Query using id from instance |
|
1097 Entry.objects.filter(blog=5) # Query using id directly |
|
1098 |
|
1099 Falling back to raw SQL |
|
1100 ======================= |
|
1101 |
|
1102 If you find yourself needing to write an SQL query that is too complex for |
|
1103 Django's database-mapper to handle, you can fall back on writing SQL by hand. |
|
1104 Django has a couple of options for writing raw SQL queries; see |
|
1105 :doc:`/topics/db/sql`. |
|
1106 |
|
1107 Finally, it's important to note that the Django database layer is merely an |
|
1108 interface to your database. You can access your database via other tools, |
|
1109 programming languages or database frameworks; there's nothing Django-specific |
|
1110 about your database. |