Django

Code

root/django/branches/magic-removal/docs/db-api.txt

Revision 2795, 48.9 kB (checked in by adrian, 3 years ago)

magic-removal: Replaced repr() with str() in docs

Line 
1 ======================
2 Database API reference
3 ======================
4
5 Once you've created your `data models`_, Django automatically gives you a
6 database-abstraction API that lets you create, retrieve, update and delete
7 objects. This document explains that API.
8
9 .. _`data models`: http://www.djangoproject.com/documentation/model_api/
10
11 Throughout this reference, we'll refer to the following models, which comprise
12 a weblog application::
13
14     class Blog(models.Model):
15         name = models.CharField(maxlength=100)
16         tagline = models.TextField()
17
18         def __str__(self):
19             return self.name
20
21     class Author(models.Model):
22         name = models.CharField(maxlength=50)
23         email = models.URLField()
24
25         class __str__(self):
26             return self.name
27
28     class Entry(models.Model):
29         blog = models.ForeignKey(Blog)
30         headline = models.CharField(maxlength=255)
31         body_text = models.TextField()
32         pub_date = models.DateTimeField()
33         authors = models.ManyToManyField(Author)
34
35         def __str__(self):
36             return self.headline
37
38 Creating objects
39 ================
40
41 To represent database-table data in Python objects, Django uses an intuitive
42 system: A model class represents a database table, and an instance of that
43 class represents a particular record in the database table.
44
45 To create an object, instantiate it using keyword arguments to the model class,
46 then call ``save()`` to save it to the database.
47
48 You import the model class from wherever it lives on the Python path, as you
49 may expect. (We point this out here because previous Django versions required
50 funky model importing.)
51
52 Assuming models live in a file ``mysite/blog/models.py``, here's an example::
53
54     from mysite.blog.models import Blog
55     b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
56     b.save()
57
58 This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
59 the database until you explicitly call ``save()``.
60
61 The ``save()`` method has no return value.
62
63 Auto-incrementing primary keys
64 ------------------------------
65
66 If a model has an ``AutoField`` -- an auto-incrementing primary key -- then
67 that auto-incremented value will be calculated and saved as an attribute on
68 your object the first time you call ``save()``.
69
70 Example::
71
72     b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
73     b2.id     # Returns None, because b doesn't have an ID yet.
74     b2.save()
75     b2.id     # Returns the ID of your new object.
76
77 There's no way to tell what the value of an ID will be before you call
78 ``save()``, because that value is calculated by your database, not by Django.
79
80 (For convenience, each model has an ``AutoField`` named ``id`` by default
81 unless you explicitly specify ``primary_key=True`` on a field. See the
82 `AutoField documentation`_.)
83
84 .. _AutoField documentation: TODO: Link
85
86 Explicitly specifying auto-primary-key values
87 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
88
89 If a model has an ``AutoField`` but you want to define a new object's ID
90 explicitly when saving, just define it explicitly before saving, rather than
91 relying on the auto-assignment of the ID.
92
93 Example::
94
95     b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
96     b3.id     # Returns 3.
97     b3.save()
98     b3.id     # Returns 3.
99
100 If you assign auto-primary-key values manually, make sure not to use an
101 already-existing primary-key value! If you create a new object with an explicit
102 primary-key value that already exists in the database, Django will assume
103 you're changing the existing record rather than creating a new one.
104
105 Given the above ``'Cheddar Talk'`` blog example, this example would override
106 the previous record in the database::
107
108     b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
109     b4.save()  # Overrides the previous blog with ID=3!
110
111 See _`How Django knows to UPDATE vs. INSERT`, below, for the reason this
112 happens.
113
114 Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
115 objects, when you're confident you won't have primary-key collision.
116
117 Saving changes to objects
118 =========================
119
120 To save changes to an object that's already in the database, use ``save()``.
121
122 Given a ``Blog`` instance ``b5`` that has already been saved to the database,
123 this example changes its name and updates its record in the database::
124
125     b5.name = 'New name'
126     b5.save()
127
128 This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
129 the database until you explicitly call ``save()``.
130
131 The ``save()`` method has no return value.
132
133 How Django knows to UPDATE vs. INSERT
134 -------------------------------------
135
136 You may have noticed Django database objects use the same ``save()`` method
137 for creating and changing objects. Django abstracts the need to use ``INSERT``
138 or ``UPDATE`` SQL statements. Specifically, when you call ``save()``, Django
139 follows this algorithm:
140
141     * If the object's primary key attribute is set to a value that evaluates to
142       ``False`` (such as ``None`` or the empty string), Django executes a
143       ``SELECT`` query to determine whether a record with the given primary key
144       already exists.
145     * If the record with the given primary key does already exist, Django
146       executes an ``UPDATE`` query.
147     * If the object's primary key attribute is *not* set, or if it's set but a
148       record doesn't exist, Django executes an ``INSERT``.
149
150 The one gotcha here is that you should be careful not to specify a primary-key
151 value explicitly when saving new objects, if you cannot guarantee the
152 primary-key value is unused. For more on this nuance, see
153 "Explicitly specifying auto-primary-key values" above.
154
155 Retrieving objects
156 ==================
157
158 To retrieve objects from your database, you construct a ``QuerySet`` via a
159 ``Manager`` on your model class.
160
161 A ``QuerySet`` represents a collection of objects from your database. It can
162 have zero, one or many *filters* -- criteria that narrow down the collection
163 based on given parameters. In SQL terms, a ``QuerySet`` equates to a ``SELECT``
164 statement, and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
165
166 You get a ``QuerySet`` by using your model's ``Manager``. Each model has at
167 least one ``Manager``, and it's called ``objects`` by default. Access it
168 directly via the model class, like so::
169
170     Blog.objects  # <django.db.models.manager.Manager object at ...>
171     b = Blog(name='Foo', tagline='Bar')
172     b.objects     # AttributeError: "Manager isn't accessible via Blog instances."
173
174 (``Managers`` are accessible only via model classes, rather than from model
175 instances, to enforce a separation between "table-level" operations and
176 "record-level" operations.)
177
178 The ``Manager`` is the main source of ``QuerySets`` for a model. It acts as a
179 "root" ``QuerySet`` that describes all objects in the model's database table.
180 For example, ``Blog.objects`` is the initial ``QuerySet`` that contains all
181 ``Blog`` objects in the database.
182
183 Retrieving all objects
184 ----------------------
185
186 The simplest way to retrieve objects from a table is to get all of them.
187 To do this, use the ``all()`` method on a ``Manager``.
188
189 Example::
190
191     all_entries = Entry.objects.all()
192
193 The ``all()`` method returns a ``QuerySet`` of all the objects in the database.
194
195 (If ``Entry.objects`` is a ``QuerySet``, why can't we just do ``Entry.objects``?
196 That's because ``Entry.objects``, the root ``QuerySet``, is a special case
197 that cannot be evaluated. The ``all()`` method returns a ``QuerySet`` that
198 *can* be evaluated.)
199
200 Filtering objects
201 -----------------
202
203 The root ``QuerySet`` provided by the ``Manager`` describes all objects in the
204 database table. Usually, though, you'll need to select only a subset of the
205 complete set of objects.
206
207 To create such a subset, you refine the initial ``QuerySet``, adding filter
208 conditions. The two most common ways to refine a ``QuerySet`` are:
209
210 ``filter(**kwargs)``
211     Returns a new ``QuerySet`` containing objects that match the given lookup
212     parameters.
213
214 ``exclude(**kwargs)``
215     Returns a new ``QuerySet`` containing objects that do *not* match the given
216     lookup parameters.
217
218 The lookup parameters (``**kwargs`` in the above function definitions) should
219 be in the format described in _`Field lookups` below.
220
221 For example, to get a ``QuerySet`` of blog entries from the year 2006, use
222 ``filter()`` like so::
223
224     Entry.objects.filter(pub_date__year=2006)
225
226 (Note we don't have to add an ``all()`` -- ``Entry.objects.all().filter(...)``.
227 That would still work, but you only need ``all()`` when you want all objects
228 from the root ``QuerySet``.)
229
230 Chaining filters
231 ~~~~~~~~~~~~~~~~
232
233 The result of refining a ``QuerySet`` is itself a ``QuerySet``, so it's
234 possible to chain refinements together. For example::
235
236     Entry.objects.filter(
237         headline__startswith='What').exclude(
238             pub_date__gte=datetime.now()).filter(
239                 pub_date__gte=datetime(2005, 1, 1))
240
241 ...takes the initial ``QuerySet`` of all entries in the database, adds a
242 filter, then an exclusion, then another filter. The final result is a
243 ``QuerySet`` containing all entries with a headline that starts with "What",
244 that were published between January 1, 2005, and the current day.
245
246 Filtered QuerySets are unique
247 -----------------------------
248
249 Each time you refine a ``QuerySet``, you get a brand-new ``QuerySet`` that is
250 in no way bound to the previous ``QuerySet``. Each refinement creates a
251 separate and distinct ``QuerySet`` that can be stored, used and reused.
252
253 Example::
254
255     q1 = Entry.objects.filter(headline__startswith="What")
256     q2 = q1.exclude(pub_date__gte=datetime.now())
257     q3 = q1.filter(pub_date__gte=datetime.now())
258
259 These three ``QuerySets`` are separate. The first is a base ``QuerySet``
260 containing all entries that contain a headline starting with "What". The second
261 is a subset of the first, with an additional criteria that excludes records
262 whose ``pub_date`` is greater than now. The third is a subset of the first,
263 with an additional criteria that selects only the records whose ``pub_date`` is
264 greater than now. The initial ``QuerySet`` (``q1``) is unaffected by the
265 refinement process.
266
267 QuerySets are lazy
268 ------------------
269
270 ``QuerySets`` are lazy -- the act of creating a ``QuerySet`` doesn't involve
271 any database activity. You can stack filters together all day long, and Django
272 won't actually run the query until the ``QuerySet`` is *evaluated*.
273
274 When QuerySets are evaluated
275 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
276
277 You can evaluate a ``QuerySet`` in the following ways:
278
279     * **Iteration.** A ``QuerySet`` is iterable, and it executes its database
280       query the first time you iterate over it. For example, this will print
281       the headline of all entries in the database::
282
283           for e in Entry.objects.all():
284               print e.headline
285
286     * **Slicing.** A ``QuerySet`` can be sliced, using Python's array-slicing
287       syntax, and it executes its database query the first time you slice it.
288       Examples::
289
290           fifth_entry = Entry.objects.all()[4]
291           all_entries_but_the_first_two = Entry.objects.all()[2:]
292           every_second_entry = Entry.objects.all()[::2]
293
294     * **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
295       This is for convenience in the Python interactive interpreter, so you can
296       immediately see your results when using the API interactively.
297
298     * **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
299       This, as you might expect, returns the length of the result list.
300
301       Note: *Don't* use ``len()`` on ``QuerySet``s if all you want to do is
302       determine the number of records in the set. It's much more efficient to
303       handle a count at the database level, using SQL's ``SELECT COUNT(*)``,
304       and Django provides a ``count()`` method for precisely this reason. See
305       ``count()`` below.
306
307     * **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
308       it. For example::
309
310           entry_list = list(Entry.objects.all())
311
312       Be warned, though, that this could have a large memory overhead, because
313       Django will load each element of the list into memory. In contrast,
314       iterating over a ``QuerySet`` will take advantage of your database to
315       load data and instantiate objects only as you need them.
316
317 QuerySet methods that return new QuerySets
318 ------------------------------------------
319
320 Django provides a range of ``QuerySet`` refinement methods that modify either
321 the types of results returned by the ``QuerySet`` or the way its SQL query is
322 executed.
323
324 filter(**kwargs)
325 ~~~~~~~~~~~~~~~~
326
327 Returns a new ``QuerySet`` containing objects that match the given lookup
328 parameters.
329
330 The lookup parameters (``**kwargs``) should be in the format described in
331 _`Field lookups` below. Multiple parameters are joined via ``AND`` in the
332 underlying SQL statement.
333
334 exclude(**kwargs)
335 ~~~~~~~~~~~~~~~~~
336
337 Returns a new ``QuerySet`` containing objects that do *not* match the given
338 lookup parameters.
339
340 The lookup parameters (``**kwargs``) should be in the format described in
341 _`Field lookups` below. Multiple parameters are joined via ``AND`` in the
342 underlying SQL statement, and the whole thing is enclosed in a ``NOT()``.
343
344 This example excludes all entries whose ``pub_date`` is the current date/time
345 AND whose ``headline`` is "Hello"::
346
347     Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
348
349 In SQL terms, that evaluates to::
350
351     SELECT ...
352     WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
353
354 This example excludes all entries whose ``pub_date`` is the current date/time
355 OR whose ``headline`` is "Hello"::
356
357     Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
358
359 In SQL terms, that evaluates to::
360
361     SELECT ...
362     WHERE NOT pub_date > '2005-1-3'
363     AND NOT headline = 'Hello'
364
365 Note the second example is more restrictive.
366
367 order_by(*fields)
368 ~~~~~~~~~~~~~~~~~
369
370 By default, results returned by a ``QuerySet`` are ordered by the ordering
371 tuple given by the ``ordering`` option in the model's ``Meta``. You can
372 override this on a per-``QuerySet`` basis by using the ``order_by`` method.
373
374 Example::
375
376     Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
377
378 The result above will be ordered by ``pub_date`` descending, then by
379 ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
380 *descending* order. Ascending order is implied. To order randomly, use ``"?"``,
381 like so::
382
383     Entry.objects.order_by('?')
384
385 To order by a field in a different table, add the other table's name and a dot,
386 like so::
387
388     Entry.objects.order_by('blogs_blog.name', 'headline')
389
390 There's no way to specify whether ordering should be case sensitive. With
391 respect to case-sensitivity, Django will order results however your database
392 backend normally orders them.
393
394 distinct()
395 ~~~~~~~~~~
396
397 Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
398 eliminates duplicate rows from the query results.
399
400 By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
401 is rarely a problem, because simple queries such as ``Blog.objects.all()``
402 don't introduce the possibility of duplicate result rows.
403
404 However, if your query spans multiple tables, it's possible to get duplicate
405 results when a ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
406
407 values(*fields)
408 ~~~~~~~~~~~~~~~
409
410 Returns a ``ValuesQuerySet`` -- a ``QuerySet`` that evaluates to a list of
411 dictionaries instead of model-instance objects.
412
413 Each of those dictionaries represents an object, with the keys corresponding to
414 the attribute names of model objects.
415
416 This example compares the dictionaries of ``values()`` with the normal model
417 objects::
418
419     # This list contains a Blog object.
420     >>> Blog.objects.filter(name__startswith='Beatles')
421     [Beatles Blog]
422
423     # This list contains a dictionary.
424     >>> Blog.objects.filter(name__startswith='Beatles').values()
425     [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
426
427 ``values()`` takes optional positional arguments, ``*fields``, which specify
428 field names to which the ``SELECT`` should be limited. If you specify the
429 fields, each dictionary will contain only the field keys/values for the fields
430 you specify. If you don't specify the fields, each dictionary will contain a
431 key and value for every field in the database table.
432
433 Example::
434
435     >>> Blog.objects.values()
436     [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
437     >>> Blog.objects.values('id', 'name')
438     [{'id': 1, 'name': 'Beatles Blog'}]
439
440 A ``ValuesQuerySet`` is useful when you know you're only going to need values
441 from a small number of the available fields and you won't need the
442 functionality of a model instance object. It's more efficient to select only
443 the fields you need to use.
444
445 Finally, note a ``ValuesQuerySet`` is a subclass of ``QuerySet``, so it has all
446 methods of ``QuerySet``. You can call ``filter()`` on it, or ``order_by()``, or
447 whatever. Yes, that means these two calls are identical::
448
449     Blog.objects.values().order_by('id')
450     Blog.objects.order_by('id').values()
451
452 The people who made Django prefer to put all the SQL-affecting methods first,
453 followed (optionally) by any output-affecting methods (such as ``values()``),
454 but it doesn't really matter. This is your chance to really flaunt your
455 individualism.
456
457 dates(field, kind, order='ASC')
458 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
459
460 Returns a ``DateQuerySet`` -- a ``QuerySet`` that evaluates to a list of
461 ``datetime.datetime`` objects representing all available dates of a particular
462 kind within the contents of the ``QuerySet``.
463
464 ``field`` should be the name of a ``DateField`` or ``DateTimeField`` of your
465 model.
466
467 ``kind`` should be either ``"year"``, ``"month"`` or ``"day"``. Each
468 ``datetime.datetime`` object in the result list is "truncated" to the given
469 ``type``.
470
471     * ``"year"`` returns a list of all distinct year values for the field.
472     * ``"month"`` returns a list of all distinct year/month values for the field.
473     * ``"day"`` returns a list of all distinct year/month/day values for the field.
474
475 ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
476 ``'DESC'``. This specifies how to order the results.
477
478 Examples::
479
480     >>> Entry.objects.dates('pub_date', 'year')
481     [datetime.datetime(2005, 1, 1)]
482     >>> Entry.objects.dates('pub_date', 'month')
483     [datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
484     >>> Entry.objects.dates('pub_date', 'day')
485     [datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
486     >>> Entry.objects.dates('pub_date', 'day', order='DESC')
487     [datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)]
488     >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
489     [datetime.datetime(2005, 3, 20)]
490
491 select_related()
492 ~~~~~~~~~~~~~~~~
493
494 Returns a ``QuerySet`` that will automatically "follow" foreign-key
495 relationships, selecting that additional related-object data when it executes
496 its query. This is a performance booster which results in (sometimes much)
497 larger queries but means later use of foreign-key relationships won't require
498 database queries.
499
500 The following examples illustrate the difference between plain lookups and
501 ``select_related()`` lookups. Here's standard lookup::
502
503     # Hits the database.
504     e = Entry.objects.get(id=5)
505
506     # Hits the database again to get the related Blog object.
507     b = e.blog
508
509 And here's ``select_related`` lookup::
510
511     # Hits the database.
512     e = Entry.objects.select_related().get(id=5)
513
514     # Doesn't hit the database, because e.blog has been prepopulated
515     # in the previous query.
516     b = e.blog
517
518 ``select_related()`` follows foreign keys as far as possible. If you have the
519 following models::
520
521     class City(models.Model):
522         # ...
523
524     class Person(models.Model):
525         # ...
526         hometown = models.ForeignKey(City)
527
528     class Book(meta.Model):
529         # ...
530         author = models.ForeignKey(Person)
531
532 ...then a call to ``Book.objects.select_related().get(id=4)`` will cache the
533 related ``Person`` *and* the related ``City``::
534
535     b = Book.objects.select_related().get(id=4)
536     p = b.author         # Doesn't hit the database.
537     c = p.hometown       # Doesn't hit the database.
538
539     sv = Book.objects.get(id=4) # No select_related() in this example.
540     p = b.author         # Hits the database.
541     c = p.hometown       # Hits the database.
542
543 extra(select=None, where=None, params=None, tables=None)
544 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
545
546 Sometimes, the Django query syntax by itself can't easily express a complex
547 ``WHERE`` clause. For these edge cases, Django provides the ``extra()``
548 ``QuerySet`` modifier -- a hook for injecting specific clauses into the SQL
549 generated by a ``QuerySet``.
550
551 By definition, these extra lookups may not be portable to different database
552 engines (because you're explicitly writing SQL code) and violate the DRY
553 principle, so you should avoid them if possible.
554
555 Specify one or more of ``params``, ``select``, ``where`` or ``tables``. None
556 of the arguments is required, but you should use at least one of them.
557
558 ``select``
559     The ``select`` argument lets you put extra fields in the ``SELECT`` clause.
560     It should be a dictionary mapping attribute names to SQL clauses to use to
561     calculate that attribute.
562
563     Example::
564
565         Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
566
567     As a result, each ``Entry`` object will have an extra attribute,
568     ``is_recent``, a boolean representing whether the entry's ``pub_date`` is
569     greater than Jan. 1, 2006.
570
571     Django inserts the given SQL snippet directly into the ``SELECT``
572     statement, so the resulting SQL of the above example would be::
573
574         SELECT blog_entry.*, (pub_date > '2006-01-01')
575         FROM blog_entry;
576
577
578     The next example is more advanced; it does a subquery to give each
579     resulting ``Blog`` object an ``entry_count`` attribute, an integer count
580     of associated ``Entry`` objects.
581
582         Blog.objects.extra(
583             select={
584                 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
585             },
586         )
587
588     (In this particular case, we're exploiting the fact that the query will
589     already contain the ``blog_blog`` table in its ``FROM`` clause.)
590
591     The resulting SQL of the above example would be::
592
593         SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id)
594         FROM blog_blog;
595
596     Note that the parenthesis required by most database engines around
597     subqueries are not required in Django's ``select`` clauses. Also note that
598     some database backends, such as some MySQL versions, don't support
599     subqueries.
600
601 ``where`` / ``tables``
602     You can define explicit SQL ``WHERE`` clauses -- perhaps to perform
603     non-explicit joins -- by using ``where``. You can manually add tables to
604     the SQL ``FROM`` clause by using ``tables``.
605
606     ``where`` and ``tables`` both take a list of strings. All ``where``
607     parameters are "AND"ed to any other search criteria.
608
609     Example::
610
611         Entry.objects.extra(where=['id IN (3, 4, 5, 20)'])
612
613     ...translates (roughly) into the following SQL::
614
615         SELECT * FROM blog_entry WHERE id IN (3, 4, 5, 20);
616
617 ``params``
618     The ``select`` and ``where`` parameters described above may use standard
619     Python database string placeholders -- ``'%s'`` to indicate parameters the
620     database engine should automatically quote. The ``params`` argument is a
621     list of any extra parameters to be substituted.
622
623     Example::
624
625         Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
626
627     Always use ``params`` instead of embedding values directly into ``select``
628     or ``where`` because ``params`` will ensure values are quoted correctly
629     according to your particular backend. (For example, quotes will be escaped
630     correctly.)
631
632     Bad::
633
634         Entry.objects.extra(where=["headline='Lennon'"])
635
636     Good::
637
638         Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
639
640 QuerySet methods that do not return QuerySets
641 ---------------------------------------------
642
643 The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
644 something *other than* a ``QuerySet``.
645
646 These methods do not use a cache (see _`Caching and QuerySets` below). Rather,
647 they query the database each time they're called.
648
649 get(**kwargs)
650 ~~~~~~~~~~~~~
651
652 Returns the object matching the given lookup parameters, which should be in
653 the format described in _`Field lookups`.
654
655 ``get()`` raises ``AssertionError`` if more than one object was found.
656
657 ``get()`` raises a ``DoesNotExist`` exception if an object wasn't found for the
658 given parameters. The ``DoesNotExist`` exception is an attribute of the model
659 class. Example::
660
661     Entry.objects.get(id='foo') # raises Entry.DoesNotExist
662
663 The ``DoesNotExist`` exception inherits from
664 ``django.core.exceptions.ObjectDoesNotExist``, so you can target multiple
665 ``DoesNotExist`` exceptions. Example::
666
667     from django.core.exceptions import ObjectDoesNotExist
668     try:
669         e = Entry.objects.get(id=3)
670         b = Blog.objects.get(id=1)
671     except ObjectDoesNotExist:
672         print "Either the entry or blog doesn't exist."
673
674 count()
675 ~~~~~~~
676
677 Returns an integer representing the number of objects in the database matching
678 the ``QuerySet``. ``count()`` never raises exceptions.
679
680 Example::
681
682     # Returns the total number of entries in the database.
683     Entry.objects.count()
684
685     # Returns the number of entries whose headline contains 'Lennon'
686     Entry.objects.filter(headline__contains='Lennon').count()
687
688 ``count()`` performs a ``SELECT COUNT(*)`` behind the scenes, so you should
689 always use ``count()`` rather than loading all of the record into Python
690 objects and calling ``len()`` on the result.
691
692 Depending on which database you're using (e.g. PostgreSQL vs. MySQL),
693 ``count()`` may return a long integer instead of a normal Python integer. This
694 is an underlying implementation quirk that shouldn't pose any real-world
695 problems.
696
697 in_bulk(id_list)
698 ~~~~~~~~~~~~~~~~
699
700 Takes a list of primary-key values and returns a dictionary mapping each
701 primary-key value to an instance of the object with the given ID.
702
703 Example::
704
705     >>> Blog.objects.in_bulk([1])
706     {1: Beatles Blog}
707     >>> Blog.objects.in_bulk([1, 2])
708     {1: Beatles Blog, 2: Cheddar Talk}
709     >>> Blog.objects.in_bulk([])
710     {}
711
712 If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.
713
714 latest(field_name=None)
715 ~~~~~~~~~~~~~~~~~~~~~~~
716
717 Returns the latest object in the table, by date, using the ``field_name``
718 provided as the date field.
719
720 This example returns the latest ``Entry`` in the table, according to the
721 ``pub_date`` field::
722
723     Entry.objects.latest('pub_date')
724
725 If your model's ``Meta`` specifies ``get_latest_by``, you can leave off the
726 ``field_name`` argument to ``latest()``. Django will use the field specified in
727 ``get_latest_by`` by default.
728
729 Like ``get()``, ``latest()`` raises ``DoesNotExist`` if an object doesn't
730 exist with the given parameters.
731
732 Note ``latest()`` exists purely for convenience and readability.
733
734 Field lookups
735 -------------
736
737 Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
738 specified as keyword arguments to the ``QuerySet`` methods ``filter()``,
739 ``exclude()`` and ``get()``.
740
741 Basic lookups keyword arguments take the form ``field__lookuptype=value``.
742 (That's a double-underscore). For example::
743
744     Entry.objects.filter(pub_date__lte='2006-01-01')
745
746 translates (roughly) into the following SQL::
747
748     SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
749
750 .. admonition:: How this is possible
751
752    Python has the ability to define functions that accept arbitrary name-value
753    arguments whose names and values are evaluated at runtime. For more
754    information, see `Keyword Arguments`_ in the official Python tutorial.
755
756    .. _`Keyword Arguments`: http://docs.python.org/tut/node6.html#SECTION006720000000000000000
757
758 If you pass an invalid keyword argument, a lookup function will raise
759 ``TypeError``.
760
761 The database API supports the following lookup types:
762
763 exact
764 ~~~~~
765
766 Exact match.
767
768 Example::
769
770     Entry.objects.get(id__exact=14)
771
772 SQL equivalent::
773
774     SELECT ... WHERE id = 14;
775
776 iexact
777 ~~~~~~
778
779 Case-insensitive exact match.
780
781 Example::
782
783     Blog.objects.get(name__iexact='beatles blog')
784
785 SQL equivalent::
786
787     SELECT ... WHERE name ILIKE 'beatles blog';
788
789 Note this will match ``'Beatles Blog'``, ``'beatles blog'``,
790 ``'BeAtLes BLoG'``, etc.
791
792 contains
793 ~~~~~~~~
794
795 Case-sensitive containment test.
796
797 Example::
798
799     Entry.objects.get(headline__contains='Lennon')
800
801 SQL equivalent::
802
803     SELECT ... WHERE headline LIKE '%Lennon%';
804
805 Note this will match the headline ``'Today Lennon honored'`` but not
806 ``'today lennon honored'``.
807
808 SQLite doesn't support case-sensitive ``LIKE`` statements; ``contains`` acts
809 like ``icontains`` for SQLite.
810
811 icontains
812 ~~~~~~~~~
813
814 Case-insensitive containment test.
815
816 Example::
817
818     Entry.objects.get(headline__icontains='Lennon')
819
820 SQL equivalent::
821
822     SELECT ... WHERE headline ILIKE '%Lennon%';
823
824 gt
825 ~~
826
827 Greater than.
828
829 Example::
830
831     Entry.objects.filter(id__gt=4)
832
833 SQL equivalent::
834
835     SELECT ... WHERE id > 4;
836
837 gte
838 ~~~
839
840 Greater than or equal to.
841
842 lt
843 ~~
844
845 Less than.
846
847 lte
848 ~~~
849
850 Less than or equal to.
851
852 in
853 ~~
854
855 In a given list.
856
857 Example::
858
859     Entry.objects.filter(id__in=[1, 3, 4])
860
861 SQL equivalent::
862
863     SELECT ... WHERE id IN (1, 3, 4);
864
865 startswith
866 ~~~~~~~~~~
867
868 Case-sensitive starts-with.
869
870 Example::
871
872     Entry.objects.filter(headline__startswith='Will')
873
874 SQL equivalent::
875
876     SELECT ... WHERE headline LIKE 'Will%';
877
878 SQLite doesn't support case-sensitive ``LIKE`` statements; ``startswith`` acts
879 like ``istartswith`` for SQLite.
880
881 istartswith
882 ~~~~~~~~~~~
883
884 Case-insensitive starts-with.
885
886 Example::
887
888     Entry.objects.filter(headline__istartswith='will')
889
890 SQL equivalent::
891
892     SELECT ... WHERE headline ILIKE 'Will%';
893
894 endswith
895 ~~~~~~~~
896
897 Case-sensitive ends-with.
898
899 Example::
900
901     Entry.objects.filter(headline__endswith='cats')
902
903 SQL equivalent::
904
905     SELECT ... WHERE headline LIKE '%cats';
906
907 SQLite doesn't support case-sensitive ``LIKE`` statements; ``endswith`` acts
908 like ``iendswith`` for SQLite.
909
910 iendswith
911 ~~~~~~~~~
912
913 Case-insensitive ends-with.
914
915 Example::
916
917     Entry.objects.filter(headline__iendswith='will')
918
919 SQL equivalent::
920
921     SELECT ... WHERE headline ILIKE '%will'
922
923 range
924 ~~~~~
925
926 Range test (inclusive).
927
928 Example::
929
930     start_date = datetime.date(2005, 1, 1)
931     end_date = datetime.date(2005, 3, 31)
932     Entry.objects.filter(pub_date__range=(start_date, end_date))
933
934 SQL equivalent::
935
936     SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
937
938 You can use ``range`` anywhere you can use ``BETWEEN`` in SQL -- for dates,
939 numbers and even characters.
940
941 year
942 ~~~~
943
944 For date/datetime fields, exact year match. Takes a four-digit year.
945
946 Example::
947
948     Entry.objects.filter(pub_date__year=2005)
949
950 SQL equivalent::
951
952     SELECT ... WHERE EXTRACT('year' FROM pub_date) = '2005';
953
954 (The exact SQL syntax varies for each database engine.)
955
956 month
957 ~~~~~
958
959 For date/datetime fields, exact month match. Takes an integer 1 (January)
960 through 12 (December).
961
962 Example::
963
964     Entry.objects.filter(pub_date__month=12)
965
966 SQL equivalent::
967
968     SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';
969
970 (The exact SQL syntax varies for each database engine.)
971
972 day
973 ~~~
974
975 For date/datetime fields, exact day match.
976
977 Example::
978
979     Entry.objects.filter(pub_date__day=3)
980
981 SQL equivalent::
982
983     SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
984
985 (The exact SQL syntax varies for each database engine.)
986
987 Note this will match any record with a pub_date on the third day of the month,
988 such as January 3, July 3, etc.
989
990 isnull
991 ~~~~~~
992
993 ``NULL`` or ``IS NOT NULL`` match. Takes either ``True`` or ``False``, which
994 correspond to ``IS NULL`` and ``IS NOT NULL``, respectively.
995
996 Example::
997
998     Entry.objects.filter(pub_date__isnull=True)
999
1000 SQL equivalent::
1001
1002     SELECT ... WHERE pub_date IS NULL;
1003
1004 Default lookups are exact
1005 ~~~~~~~~~~~~~~~~~~~~~~~~~
1006
1007 If you don't provide a lookup type -- that is, if your keyword argument doesn't
1008 contain a double underscore -- the lookup type is assumed to be ``exact``.
1009
1010 For example, the following two statements are equivalent::
1011
1012     Blog.objects.get(id=14)
1013     Blog.objects.get(id__exact=14)
1014
1015 This is for convenience, because ``exact`` lookups are the common case.
1016
1017 The pk lookup shortcut
1018 ~~~~~~~~~~~~~~~~~~~~~~
1019
1020 For convenience, Django provides a ``pk`` lookup type, which stands for
1021 "primary_key". This is shorthand for "an exact lookup on the primary-key."
1022
1023 In the example ``Blog`` model, the primary key is the ``id`` field, so these
1024 two statements are equivalent::
1025
1026     Blog.objects.get(id__exact=14)
1027     Blog.objects.get(pk=14)
1028
1029 ``pk`` lookups also work across joins. For example, these two statements are
1030 equivalent::
1031
1032     Entry.objects.filter(blog__id__exact=3)
1033     Entry.objects.filter(blog__pk=3)
1034
1035 Escaping parenthesis and underscores in LIKE statements
1036 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1037
1038 The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
1039 ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
1040 and ``iendswith``) will automatically escape the two special characters used in
1041 ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
1042 statement, the percent sign signifies a multiple-character wildcard and the
1043 underscore signifies a single-character wildcard.)
1044
1045 This means things should work intuitively, so the abstraction doesn't leak.
1046 For example, to retrieve all the entries that contain a percent sign, just use
1047 the percent sign as any other character::
1048
1049     Entry.objects.filter(headline__contains='%')
1050
1051 Django takes care of the quoting for you; the resulting SQL will look something
1052 like this::
1053
1054     SELECT ... WHERE headline LIKE '%\%%';
1055
1056 Same goes for underscores. Both percentage signs and underscores are handled
1057 for you transparently.
1058
1059 Caching and QuerySets
1060 ---------------------
1061
1062 Each ``QuerySet`` contains a cache, to minimize database access. It's important
1063 to understand how it works, in order to write the most efficient code.
1064
1065 In a newly created ``QuerySet``, the cache is empty. The first time a
1066 ``QuerySet`` is evaluated -- and, hence, a database query happens -- Django
1067 saves the query results in the ``QuerySet``'s cache and returns the results
1068 that have been explicitly requested (e.g., the next element, if the
1069 ``QuerySet`` is being iterated over). Subsequent evaluations of the
1070 ``QuerySet`` reuse the cached results.
1071
1072 Keep this caching behavior in mind, because it may bite you if you don't use
1073 your ``QuerySet``s correctly. For example, the following will create two
1074 ``QuerySet``s, evaluate them, and throw them away::
1075
1076     print [e.headline for e in Entry.objects.all()]
1077     print [e.pub_date for e in Entry.objects.all()]
1078
1079 That means the same database query will be executed twice, effectively doubling
1080 your database load. Also, there's a possibility the two lists may not include
1081 the same database records, because an ``Entry`` may have been added or deleted
1082 in the split second between the two requests.
1083
1084 To avoid this problem, simply save the ``QuerySet`` and reuse it::
1085
1086     queryset = Poll.objects.all()
1087     print [p.headline for p in queryset] # Evaluate the query set.
1088     print [p.pub_date for p in queryset] # Re-use the cache from the evaluation.
1089
1090 Comparing objects
1091 =================
1092
1093 To compare two model instances, just use the standard Python comparison operator,
1094 the double equals sign: ``==``. Behind the scenes, that compares the primary
1095 key values of two models.
1096
1097 Using the ``Entry`` example above, the following two statements are equivalent::
1098
1099     some_entry == other_entry
1100     some_entry.id == other_entry.id
1101
1102 If a model's primary key isn't called ``id``, no problem. Comparisons will
1103 always use the primary key, whatever it's called. For example, if a model's
1104 primary key field is called ``name``, these two statements are equivalent::
1105
1106     some_obj == other_obj
1107     some_obj.name == other_obj.name
1108
1109
1110
1111
1112 ========================================
1113 THE REST OF THIS HAS NOT YET BEEN EDITED
1114 ========================================
1115
1116
1117 OR lookups
1118 ==========
1119
1120 Keyword argument queries are "AND"ed together. If you have more
1121 complex query requirements (for example, you need to include an ``OR``
1122 statement in your query), you need to use ``Q`` objects.
1123
1124 A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a
1125 collection of keyword arguments. These keyword arguments are specified in
1126 the same way as keyword arguments to the basic lookup functions like get()
1127 and filter(). For example::
1128
1129     Q(question__startswith='What')
1130
1131 is a ``Q`` object encapsulating a single ``LIKE`` query. ``Q`` objects can be
1132 combined using the ``&`` and ``|`` operators. When an operator is used on two
1133 ``Q`` objects, it yields a new ``Q`` object. For example the statement::
1134
1135     Q(question__startswith='Who') | Q(question__startswith='What')
1136
1137 ... yields a single ``Q`` object that represents the "OR" of two
1138 "question__startswith" queries, equivalent to the SQL WHERE clause::
1139
1140     ... WHERE question LIKE 'Who%' OR question LIKE 'What%'
1141
1142 You can compose statements of arbitrary complexity by combining ``Q`` objects
1143 with the ``&`` and ``|`` operators. Parenthetical grouping can also be used.
1144
1145 One or more ``Q`` objects can then provided as arguments to the lookup
1146 functions. If multiple ``Q`` object arguments are provided to a lookup
1147 function, they will be "AND"ed together. For example::
1148
1149     Poll.objects.get(
1150         Q(question__startswith='Who'),
1151         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
1152     )
1153
1154 ... roughly translates into the SQL::
1155
1156     SELECT * from polls WHERE question LIKE 'Who%'
1157         AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
1158
1159 If necessary, lookup functions can mix the use of ``Q`` objects and keyword
1160 arguments. All arguments provided to a lookup function (be they keyword
1161 argument or ``Q`` object) are "AND"ed together. However, if a ``Q`` object is
1162 provided, it must precede the definition of any keyword arguments. For
1163 example::
1164
1165     Poll.objects.get(
1166         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
1167         question__startswith='Who')
1168
1169 ... would be a valid query, equivalent to the previous example; but::
1170
1171     # INVALID QUERY
1172     Poll.objects.get(
1173         question__startswith='Who',
1174         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
1175
1176 ... would not be valid.
1177
1178 A ``Q`` objects can also be provided to the ``complex`` keyword argument. For example::
1179
1180     Poll.objects.get(
1181         complex=Q(question__startswith='Who') &
1182             (Q(pub_date=date(2005, 5, 2)) |
1183              Q(pub_date=date(2005, 5, 6))
1184         )
1185     )
1186
1187 See the `OR lookups examples page`_ for more examples.
1188
1189 .. _OR lookups examples page: http://www.djangoproject.com/documentation/models/or_lookups/
1190
1191
1192 Relationships (joins)
1193 =====================
1194
1195 When you define a relationship in a model (i.e., a ForeignKey,
1196 OneToOneField, or ManyToManyField), Django uses the name of the
1197 relationship to add a descriptor_ on every instance of the model.
1198 This descriptor behaves just like a normal attribute, providing
1199 access to the related object or objects.  For example,
1200 ``mychoice.poll`` will return the poll object associated with a specific
1201 instance of ``Choice``.
1202
1203 .. _descriptor: http://users.rcn.com/python/download/Descriptor.htm
1204
1205 Django also adds a descriptor for the 'other' side of the relationship -
1206 the link from the related model to the model that defines the relationship.
1207 Since the related model has no explicit reference to the source model,
1208 Django will automatically derive a name for this descriptor. The name that
1209 Django chooses depends on the type of relation that is represented. However,
1210 if the definition of the relation has a `related_name` parameter, Django
1211 will use this name in preference to deriving a name.
1212
1213 There are two types of descriptor that can be employed: Single Object
1214 Descriptors and Object Set Descriptors. The following table describes
1215 when each descriptor type is employed. The local model is the model on
1216 which the relation is defined; the related model is the model referred
1217 to by the relation.
1218
1219     =============== ============= =============
1220     Relation Type   Local Model   Related Model
1221     =============== ============= =============
1222