Django

Code

root/django/branches/per-object-permissions/docs/db-api.txt

Revision 5488, 62.0 kB (checked in by clong, 1 year ago)

per-object-permissions: Merged to trunk [5486] NOTE: Not fully tested, will be working on this over the next few weeks.

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