Fixed #8730: Incorporated (with minor changes) additions/enhancements to one-to-one...
[django.git] / docs / topics / db / queries.txt
blobbf87b6132896db4c702a6fe3ddd5a8847efc2dc2
1 .. _topics-db-queries:
3 ==============
4 Making queries
5 ==============
7 .. currentmodule:: django.db.models
9 Once you've created your :ref:`data models <topics-db-models>`, Django
10 automatically gives you a database-abstraction API that lets you create,
11 retrieve, update and delete objects. This document explains how to use this 
12 API. Refer to the `data model reference <ref-models-index>` for full 
13 details of all the various model lookup options.
15 Throughout this guide (and in the reference), we'll refer to the following
16 models, which comprise a weblog application:
18 .. _queryset-model-example:
20 .. code-block:: python
22     class Blog(models.Model):
23         name = models.CharField(max_length=100)
24         tagline = models.TextField()
26         def __unicode__(self):
27             return self.name
29     class Author(models.Model):
30         name = models.CharField(max_length=50)
31         email = models.EmailField()
33         def __unicode__(self):
34             return self.name
36     class Entry(models.Model):
37         blog = models.ForeignKey(Blog)
38         headline = models.CharField(max_length=255)
39         body_text = models.TextField()
40         pub_date = models.DateTimeField()
41         authors = models.ManyToManyField(Author)
43         def __unicode__(self):
44             return self.headline
46 Creating objects
47 ================
49 To represent database-table data in Python objects, Django uses an intuitive
50 system: A model class represents a database table, and an instance of that
51 class represents a particular record in the database table.
53 To create an object, instantiate it using keyword arguments to the model class,
54 then call ``save()`` to save it to the database.
56 You import the model class from wherever it lives on the Python path, as you
57 may expect. (We point this out here because previous Django versions required
58 funky model importing.)
60 Assuming models live in a file ``mysite/blog/models.py``, here's an example::
62     >>> from mysite.blog.models import Blog
63     >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
64     >>> b.save()
66 This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
67 the database until you explicitly call ``save()``.
69 The ``save()`` method has no return value.
71 .. seealso::
73     ``save()`` takes a number of advanced options not described here.
74     See the documentation for ``save()`` for complete details.
76     To create an object and save it all in one step see the ```create()```
77     method.
79 Saving changes to objects
80 =========================
82 To save changes to an object that's already in the database, use ``save()``.
84 Given a ``Blog`` instance ``b5`` that has already been saved to the database,
85 this example changes its name and updates its record in the database::
87     >> b5.name = 'New name'
88     >> b5.save()
90 This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
91 the database until you explicitly call ``save()``.
93 Saving ``ForeignKey`` and ``ManyToManyField`` fields
94 ----------------------------------------------------
96 Updating ``ForeignKey`` fields works exactly the same way as saving a normal
97 field; simply assign an object of the right type to the field in question:: 
99     >>> cheese_blog = Blog.objects.get(name="Cheddar Talk") 
100     >>> entry.blog = cheese_blog 
101     >>> entry.save() 
103 Updating a ``ManyToManyField`` works a little differently; use the ``add()``
104 method on the field to add a record to the relation::
106     >> joe = Author.objects.create(name="Joe")
107     >> entry.authors.add(joe)
109 Django will complain if you try to assign or add an object of the wrong type.
111 Retrieving objects
112 ==================
114 To retrieve objects from your database, you construct a ``QuerySet`` via a
115 ``Manager`` on your model class.
117 A ``QuerySet`` represents a collection of objects from your database. It can
118 have zero, one or many *filters* -- criteria that narrow down the collection
119 based on given parameters. In SQL terms, a ``QuerySet`` equates to a ``SELECT``
120 statement, and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
122 You get a ``QuerySet`` by using your model's ``Manager``. Each model has at
123 least one ``Manager``, and it's called ``objects`` by default. Access it
124 directly via the model class, like so::
126     >>> Blog.objects
127     <django.db.models.manager.Manager object at ...>
128     >>> b = Blog(name='Foo', tagline='Bar')
129     >>> b.objects
130     Traceback:
131         ...
132     AttributeError: "Manager isn't accessible via Blog instances."
134 .. note::
136     ``Managers`` are accessible only via model classes, rather than from model
137     instances, to enforce a separation between "table-level" operations and
138     "record-level" operations.
140 The ``Manager`` is the main source of ``QuerySets`` for a model. It acts as a
141 "root" ``QuerySet`` that describes all objects in the model's database table.
142 For example, ``Blog.objects`` is the initial ``QuerySet`` that contains all
143 ``Blog`` objects in the database.
145 Retrieving all objects
146 ----------------------
148 The simplest way to retrieve objects from a table is to get all of them.
149 To do this, use the ``all()`` method on a ``Manager``::
151     >>> all_entries = Entry.objects.all()
153 The ``all()`` method returns a ``QuerySet`` of all the objects in the database.
155 (If ``Entry.objects`` is a ``QuerySet``, why can't we just do ``Entry.objects``?
156 That's because ``Entry.objects``, the root ``QuerySet``, is a special case
157 that cannot be evaluated. The ``all()`` method returns a ``QuerySet`` that
158 *can* be evaluated.)
160 Retrieving specific objects with filters
161 ----------------------------------------
163 The root ``QuerySet`` provided by the ``Manager`` describes all objects in the
164 database table. Usually, though, you'll need to select only a subset of the
165 complete set of objects.
167 To create such a subset, you refine the initial ``QuerySet``, adding filter
168 conditions. The two most common ways to refine a ``QuerySet`` are:
170     ``filter(**kwargs)``
171         Returns a new ``QuerySet`` containing objects that match the given
172         lookup parameters.
174     ``exclude(**kwargs)``
175         Returns a new ``QuerySet`` containing objects that do *not* match the
176         given lookup parameters.
178 The lookup parameters (``**kwargs`` in the above function definitions) should
179 be in the format described in `Field lookups`_ below.
181 For example, to get a ``QuerySet`` of blog entries from the year 2006, use
182 ``filter()`` like so::
184     Entry.objects.filter(pub_date__year=2006)
186 We don't have to add an ``all()`` -- ``Entry.objects.all().filter(...)``. That
187 would still work, but you only need ``all()`` when you want all objects from the
188 root ``QuerySet``.
190 .. _chaining-filters:
192 Chaining filters
193 ~~~~~~~~~~~~~~~~
195 The result of refining a ``QuerySet`` is itself a ``QuerySet``, so it's
196 possible to chain refinements together. For example::
198     >>> Entry.objects.filter(
199     ...     headline__startswith='What'
200     ... ).exclude(
201     ...     pub_date__gte=datetime.now()
202     ... ).filter(
203     ...     pub_date__gte=datetime(2005, 1, 1)
204     ... )
206 This takes the initial ``QuerySet`` of all entries in the database, adds a
207 filter, then an exclusion, then another filter. The final result is a
208 ``QuerySet`` containing all entries with a headline that starts with "What",
209 that were published between January 1, 2005, and the current day.
211 .. _filtered-querysets-are-unique:
213 Filtered QuerySets are unique
214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
216 Each time you refine a ``QuerySet``, you get a brand-new ``QuerySet`` that is
217 in no way bound to the previous ``QuerySet``. Each refinement creates a
218 separate and distinct ``QuerySet`` that can be stored, used and reused.
220 Example::
222     >> q1 = Entry.objects.filter(headline__startswith="What")
223     >> q2 = q1.exclude(pub_date__gte=datetime.now())
224     >> q3 = q1.filter(pub_date__gte=datetime.now())
226 These three ``QuerySets`` are separate. The first is a base ``QuerySet``
227 containing all entries that contain a headline starting with "What". The second
228 is a subset of the first, with an additional criteria that excludes records
229 whose ``pub_date`` is greater than now. The third is a subset of the first,
230 with an additional criteria that selects only the records whose ``pub_date`` is
231 greater than now. The initial ``QuerySet`` (``q1``) is unaffected by the
232 refinement process.
234 .. _querysets-are-lazy:
236 QuerySets are lazy
237 ~~~~~~~~~~~~~~~~~~
239 ``QuerySets`` are lazy -- the act of creating a ``QuerySet`` doesn't involve any
240 database activity. You can stack filters together all day long, and Django won't
241 actually run the query until the ``QuerySet`` is *evaluated*. Take a look at
242 this example::
244     >>> q = Entry.objects.filter(headline__startswith="What")
245     >>> q = q.filter(pub_date__lte=datetime.now())
246     >>> q = q.exclude(body_text__icontains="food")
247     >>> print q
248     
249 Though this looks like three database hits, in fact it hits the database only
250 once, at the last line (``print q``). In general, the results of a ``QuerySet``
251 aren't fetched from the database until you "ask" for them. When you do, the
252 ``QuerySet`` is *evaluated* by accessing the database. For more details on
253 exactly when evaluation takes place, see :ref:`when-querysets-are-evaluated`.
255 Other QuerySet methods
256 ~~~~~~~~~~~~~~~~~~~~~~
258 Most of the time you'll use ``all()``, ``filter()`` and ``exclude()`` when you
259 need to look up objects from the database. However, that's far from all there is; see the :ref:`QuerySet API Reference <queryset-api>` for a complete list
260 of all the various ``QuerySet`` methods.
262 .. _limiting-querysets:
264 Limiting QuerySets
265 ------------------
267 Use Python's array-slicing syntax to limit your ``QuerySet`` to a certain
268 number of results. This is the equivalent of SQL's ``LIMIT`` and ``OFFSET``
269 clauses.
271 For example, this returns the first 5 objects (``LIMIT 5``)::
273     >>> Entry.objects.all()[:5]
275 This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::
277     >>> Entry.objects.all()[5:10]
279 Generally, slicing a ``QuerySet`` returns a new ``QuerySet`` -- it doesn't
280 evaluate the query. An exception is if you use the "step" parameter of Python
281 slice syntax. For example, this would actually execute the query in order to
282 return a list of every *second* object of the first 10::
284     >>> Entry.objects.all()[:10:2]
286 To retrieve a *single* object rather than a list
287 (e.g. ``SELECT foo FROM bar LIMIT 1``), use a simple index instead of a
288 slice. For example, this returns the first ``Entry`` in the database, after
289 ordering entries alphabetically by headline::
291     >>> Entry.objects.order_by('headline')[0]
293 This is roughly equivalent to::
295     >>> Entry.objects.order_by('headline')[0:1].get()
297 Note, however, that the first of these will raise ``IndexError`` while the
298 second will raise ``DoesNotExist`` if no objects match the given criteria. See
299 ``get()`` for more details.
301 .. _field-lookups-intro:
303 Field lookups
304 -------------
306 Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
307 specified as keyword arguments to the ``QuerySet`` methods ``filter()``,
308 ``exclude()`` and ``get()``.
310 Basic lookups keyword arguments take the form ``field__lookuptype=value``.
311 (That's a double-underscore). For example::
313     >>> Entry.objects.filter(pub_date__lte='2006-01-01')
315 translates (roughly) into the following SQL::
317     SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
319 .. admonition:: How this is possible
321    Python has the ability to define functions that accept arbitrary name-value
322    arguments whose names and values are evaluated at runtime. For more
323    information, see `Keyword Arguments`_ in the official Python tutorial.
325    .. _`Keyword Arguments`: http://docs.python.org/tut/node6.html#SECTION006720000000000000000
327 If you pass an invalid keyword argument, a lookup function will raise
328 ``TypeError``.
330 The database API supports about two dozen lookup types; a complete reference
331 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
332 you'll probably use:
334     :lookup:`exact`
335         An "exact" match. For example::
336         
337             >>> Entry.objects.get(headline__exact="Man bites dog")
339         World generate SQL along these lines:
340         
341         .. code-block:: sql
343             SELECT ... WHERE headline = 'Man bits dog';
344             
345         If you don't provide a lookup type -- that is, if your keyword argument
346         doesn't contain a double underscore -- the lookup type is assumed to be
347         ``exact``.
349         For example, the following two statements are equivalent::
351             >>> Blog.objects.get(id__exact=14)  # Explicit form
352             >>> Blog.objects.get(id=14)         # __exact is implied
354         This is for convenience, because ``exact`` lookups are the common case.
355         
356     :lookup:`iexact`
357         A case-insensitive match. So, the query::
358         
359             >>> Blog.objects.get(name__iexact="beatles blog")
360             
361         Would match a ``Blog`` titled "Beatles Blog", "beatles blog", or even
362         "BeAtlES blOG".
363     
364     :lookup:`contains`
365         Case-sensitive containment test. For example::
367             Entry.objects.get(headline__contains='Lennon')
369         Roughly translates to this SQL:
370         
371         .. code-block:: sql
373             SELECT ... WHERE headline LIKE '%Lennon%';
375         Note this will match the headline ``'Today Lennon honored'`` but not
376         ``'today lennon honored'``.
377         
378         There's also a case-insensitive version, :lookup:`icontains`.
379         
380     :lookup:`startswith`, :lookup:`endswith`
381         Starts-with and ends-with search, respectively. There are also
382         case-insensitive versions called :lookup:`istartswith` and
383         :lookup:`iendswith`.
384     
385 Again, this only scratches the surface. A complete reference can be found in the
386 :ref:`field lookup reference <field-lookups>`.
388 Lookups that span relationships
389 -------------------------------
391 Django offers a powerful and intuitive way to "follow" relationships in
392 lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the
393 scenes. To span a relationship, just use the field name of related fields
394 across models, separated by double underscores, until you get to the field you
395 want.
397 This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
398 is ``'Beatles Blog'``::
400     >>> Entry.objects.filter(blog__name__exact='Beatles Blog')
402 This spanning can be as deep as you'd like.
404 It works backwards, too. To refer to a "reverse" relationship, just use the
405 lowercase name of the model.
407 This example retrieves all ``Blog`` objects which have at least one ``Entry``
408 whose ``headline`` contains ``'Lennon'``::
410     >>> Blog.objects.filter(entry__headline__contains='Lennon')
412 If you are filtering across multiple relationships and one of the intermediate
413 models doesn't have a value that meets the filter condition, Django will treat
414 it as if there is an empty (all values are ``NULL``), but valid, object there.
415 All this means is that no error will be raised. For example, in this filter::
417     Blog.objects.filter(entry__author__name='Lennon')
419 (if there was a related ``Author`` model), if there was no ``author``
420 associated with an entry, it would be treated as if there was also no ``name``
421 attached, rather than raising an error because of the missing ``author``.
422 Usually this is exactly what you want to have happen. The only case where it
423 might be confusing is if you are using ``isnull``. Thus::
425     Blog.objects.filter(entry__author__name__isnull=True)
427 will return ``Blog`` objects that have an empty ``name`` on the ``author`` and
428 also those which have an empty ``author`` on the ``entry``. If you don't want
429 those latter objects, you could write::
431     Blog.objetcs.filter(entry__author__isnull=False,
432             entry__author__name__isnull=True)
434 Spanning multi-valued relationships
435 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
437 **New in Django development version**
439 When you are filtering an object based on a ``ManyToManyField`` or a reverse
440 ``ForeignKeyField``, there are two different sorts of filter you may be
441 interested in. Consider the ``Blog``/``Entry`` relationship (``Blog`` to
442 ``Entry`` is a one-to-many relation). We might be interested in finding blogs
443 that have an entry which has both *"Lennon"* in the headline and was published
444 in 2008. Or we might want to find blogs that have an entry with *"Lennon"* in
445 the headline as well as an entry that was published in 2008. Since there are
446 multiple entries associated with a single ``Blog``, both of these queries are
447 possible and make sense in some situations.
449 The same type of situation arises with a ``ManyToManyField``. For example, if
450 an ``Entry`` has a ``ManyToManyField`` called ``tags``, we might want to find
451 entries linked to tags called *"music"* and *"bands"* or we might want an
452 entry that contains a tag with a name of *"music"* and a status of *"public"*.
454 To handle both of these situations, Django has a consistent way of processing
455 ``filter()`` and ``exclude()`` calls. Everything inside a single ``filter()``
456 call is applied simultaneously to filter out items matching all those
457 requirements. Successive ``filter()`` calls further restrict the set of
458 objects, but for multi-valued relations, they apply to any object linked to
459 the primary model, not necessarily those objects that were selected by an
460 earlier ``filter()`` call.
462 That may sound a bit confusing, so hopefully an example will clarify. To
463 select all blogs that contains entries with *"Lennon"* in the headline and
464 were published in 2008, we would write::
466     Blog.objects.filter(entry__headline__contains='Lennon',
467             entry__pub_date__year=2008)
469 To select all blogs that contain an entry with *"Lennon"* in the headline
470 **as well as** an entry that was published in 2008, we would write::
472     Blog.objects.filter(entry__headline__contains='Lennon').filter(
473             entry__pub_date__year=2008)
475 In this second example, the first filter restricted the queryset to all those
476 blogs linked to that particular type of entry. The second filter restricted
477 the set of blogs *further* to those that are also linked to the second type of
478 entry. The entries select by the second filter may or may not be the same as
479 the entries in the first filter. We are filtering the ``Blog`` items with each
480 filter statement, not the ``Entry`` items.
482 All of this behavior also applies to ``exclude()``: all the conditions in a
483 single ``exclude()`` statement apply to a single instance (if those conditions
484 are talking about the same multi-valued relation). Conditions in subsequent
485 ``filter()`` or ``exclude()`` calls that refer to the same relation may end up
486 filtering on different linked objects.
488 The pk lookup shortcut
489 ----------------------
491 For convenience, Django provides a ``pk`` lookup shortcut, which stands for
492 "primary key".
494 In the example ``Blog`` model, the primary key is the ``id`` field, so these
495 three statements are equivalent::
497     >>> Blog.objects.get(id__exact=14) # Explicit form
498     >>> Blog.objects.get(id=14) # __exact is implied
499     >>> Blog.objects.get(pk=14) # pk implies id__exact
501 The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
502 can be combined with ``pk`` to perform a query on the primary key of a model::
504     # Get blogs entries with id 1, 4 and 7
505     >>> Blog.objects.filter(pk__in=[1,4,7])
506     
507     # Get all blog entries with id > 14
508     >>> Blog.objects.filter(pk__gt=14)
510 ``pk`` lookups also work across joins. For example, these three statements are
511 equivalent::
513     >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
514     >>> Entry.objects.filter(blog__id=3)        # __exact is implied
515     >>> Entry.objects.filter(blog__pk=3)        # __pk implies __id__exact
517 Escaping percent signs and underscores in LIKE statements
518 ---------------------------------------------------------
520 The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
521 ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
522 and ``iendswith``) will automatically escape the two special characters used in
523 ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
524 statement, the percent sign signifies a multiple-character wildcard and the
525 underscore signifies a single-character wildcard.)
527 This means things should work intuitively, so the abstraction doesn't leak.
528 For example, to retrieve all the entries that contain a percent sign, just use
529 the percent sign as any other character::
531     >>> Entry.objects.filter(headline__contains='%')
533 Django takes care of the quoting for you; the resulting SQL will look something
534 like this:
536 .. code-block:: sql
538     SELECT ... WHERE headline LIKE '%\%%';
540 Same goes for underscores. Both percentage signs and underscores are handled
541 for you transparently.
543 .. _caching-and-querysets:
545 Caching and QuerySets
546 ---------------------
548 Each ``QuerySet`` contains a cache, to minimize database access. It's important
549 to understand how it works, in order to write the most efficient code.
551 In a newly created ``QuerySet``, the cache is empty. The first time a
552 ``QuerySet`` is evaluated -- and, hence, a database query happens -- Django
553 saves the query results in the ``QuerySet``'s cache and returns the results
554 that have been explicitly requested (e.g., the next element, if the
555 ``QuerySet`` is being iterated over). Subsequent evaluations of the
556 ``QuerySet`` reuse the cached results.
558 Keep this caching behavior in mind, because it may bite you if you don't use
559 your ``QuerySet``\s correctly. For example, the following will create two
560 ``QuerySet``\s, evaluate them, and throw them away::
562     >>> print [e.headline for e in Entry.objects.all()]
563     >>> print [e.pub_date for e in Entry.objects.all()]
565 That means the same database query will be executed twice, effectively doubling
566 your database load. Also, there's a possibility the two lists may not include
567 the same database records, because an ``Entry`` may have been added or deleted
568 in the split second between the two requests.
570 To avoid this problem, simply save the ``QuerySet`` and reuse it::
572     >>> queryset = Poll.objects.all()
573     >>> print [p.headline for p in queryset] # Evaluate the query set.
574     >>> print [p.pub_date for p in queryset] # Re-use the cache from the evaluation.
576 Complex lookups with Q objects
577 ==============================
579 Keyword argument queries -- in ``filter()``, etc. -- are "AND"ed together. If
580 you need to execute more complex queries (for example, queries with ``OR``
581 statements), you can use ``Q`` objects.
583 A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a
584 collection of keyword arguments. These keyword arguments are specified as in
585 "Field lookups" above.
587 For example, this ``Q`` object encapsulates a single ``LIKE`` query::
589     Q(question__startswith='What')
591 ``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
592 operator is used on two ``Q`` objects, it yields a new ``Q`` object.
594 For example, this statement yields a single ``Q`` object that represents the
595 "OR" of two ``"question__startswith"`` queries::
597     Q(question__startswith='Who') | Q(question__startswith='What')
599 This is equivalent to the following SQL ``WHERE`` clause::
601     WHERE question LIKE 'Who%' OR question LIKE 'What%'
603 You can compose statements of arbitrary complexity by combining ``Q`` objects
604 with the ``&`` and ``|`` operators. You can also use parenthetical grouping.
606 Each lookup function that takes keyword-arguments (e.g. ``filter()``,
607 ``exclude()``, ``get()``) can also be passed one or more ``Q`` objects as
608 positional (not-named) arguments. If you provide multiple ``Q`` object
609 arguments to a lookup function, the arguments will be "AND"ed together. For
610 example::
612     Poll.objects.get(
613         Q(question__startswith='Who'),
614         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
615     )
617 ... roughly translates into the SQL::
619     SELECT * from polls WHERE question LIKE 'Who%'
620         AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
622 Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
623 arguments provided to a lookup function (be they keyword arguments or ``Q``
624 objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
625 precede the definition of any keyword arguments. For example::
627     Poll.objects.get(
628         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
629         question__startswith='Who')
631 ... would be a valid query, equivalent to the previous example; but::
633     # INVALID QUERY
634     Poll.objects.get(
635         question__startswith='Who',
636         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
638 ... would not be valid.
640 .. seealso::
642     The `OR lookups examples`_ show some possible uses of ``Q``.
644     .. _OR lookups examples: http://www.djangoproject.com/models/or_lookups/
646 Comparing objects
647 =================
649 To compare two model instances, just use the standard Python comparison operator,
650 the double equals sign: ``==``. Behind the scenes, that compares the primary
651 key values of two models.
653 Using the ``Entry`` example above, the following two statements are equivalent::
655     >>> some_entry == other_entry
656     >>> some_entry.id == other_entry.id
658 If a model's primary key isn't called ``id``, no problem. Comparisons will
659 always use the primary key, whatever it's called. For example, if a model's
660 primary key field is called ``name``, these two statements are equivalent::
662     >>> some_obj == other_obj
663     >>> some_obj.name == other_obj.name
665 Deleting objects
666 ================
668 The delete method, conveniently, is named ``delete()``. This method immediately
669 deletes the object and has no return value. Example::
671     e.delete()
673 You can also delete objects in bulk. Every ``QuerySet`` has a ``delete()``
674 method, which deletes all members of that ``QuerySet``.
676 For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
677 2005::
679     Entry.objects.filter(pub_date__year=2005).delete()
681 Keep in mind that this will, whenever possible, be executed purely in
682 SQL, and so the ``delete()`` methods of individual object instances
683 will not necessarily be called during the process. If you've provided
684 a custom ``delete()`` method on a model class and want to ensure that
685 it is called, you will need to "manually" delete instances of that
686 model (e.g., by iterating over a ``QuerySet`` and calling ``delete()``
687 on each object individually) rather than using the bulk ``delete()``
688 method of a ``QuerySet``.
690 When Django deletes an object, it emulates the behavior of the SQL
691 constraint ``ON DELETE CASCADE`` -- in other words, any objects which
692 had foreign keys pointing at the object to be deleted will be deleted
693 along with it. For example::
695     b = Blog.objects.get(pk=1)
696     # This will delete the Blog and all of its Entry objects.
697     b.delete()
699 Note that ``delete()`` is the only ``QuerySet`` method that is not exposed on a
700 ``Manager`` itself. This is a safety mechanism to prevent you from accidentally
701 requesting ``Entry.objects.delete()``, and deleting *all* the entries. If you
702 *do* want to delete all the objects, then you have to explicitly request a
703 complete query set::
705     Entry.objects.all().delete()
707 Updating multiple objects at once
708 =================================
710 **New in Django development version**
712 Sometimes you want to set a field to a particular value for all the objects in
713 a ``QuerySet``. You can do this with the ``update()`` method. For example::
715     # Update all the headlines with pub_date in 2007.
716     Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
718 You can only set non-relation fields and ``ForeignKey`` fields using this
719 method, and the value you set the field to must be a hard-coded Python value
720 (i.e., you can't set a field to be equal to some other field at the moment).
722 To update ``ForeignKey`` fields, set the new value to be the new model
723 instance you want to point to. Example::
725     >>> b = Blog.objects.get(pk=1)
726     
727     # Change every Entry so that it belongs to this Blog.
728     >>> Entry.objects.all().update(blog=b)
730 The ``update()`` method is applied instantly and doesn't return anything
731 (similar to ``delete()``). The only restriction on the ``QuerySet`` that is
732 updated is that it can only access one database table, the model's main
733 table. So don't try to filter based on related fields or anything like that;
734 it won't work.
736 Be aware that the ``update()`` method is converted directly to an SQL
737 statement. It is a bulk operation for direct updates. It doesn't run any
738 ``save()`` methods on your models, or emit the ``pre_save`` or ``post_save``
739 signals (which are a consequence of calling ``save()``). If you want to save
740 every item in a ``QuerySet`` and make sure that the ``save()`` method is
741 called on each instance, you don't need any special function to handle that.
742 Just loop over them and call ``save()``::
744     for item in my_queryset:
745         item.save()
747 Related objects
748 ===============
750 When you define a relationship in a model (i.e., a ``ForeignKey``,
751 ``OneToOneField``, or ``ManyToManyField``), instances of that model will have
752 a convenient API to access the related object(s).
754 Using the models at the top of this page, for example, an ``Entry`` object ``e``
755 can get its associated ``Blog`` object by accessing the ``blog`` attribute:
756 ``e.blog``.
758 (Behind the scenes, this functionality is implemented by Python descriptors_.
759 This shouldn't really matter to you, but we point it out here for the curious.)
761 Django also creates API accessors for the "other" side of the relationship --
762 the link from the related model to the model that defines the relationship.
763 For example, a ``Blog`` object ``b`` has access to a list of all related
764 ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
766 All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
767 models defined at the top of this page.
769 .. _descriptors: http://users.rcn.com/python/download/Descriptor.htm
771 One-to-many relationships
772 -------------------------
774 Forward
775 ~~~~~~~
777 If a model has a ``ForeignKey``, instances of that model will have access to
778 the related (foreign) object via a simple attribute of the model.
780 Example::
782     >>> e = Entry.objects.get(id=2)
783     >>> e.blog # Returns the related Blog object.
785 You can get and set via a foreign-key attribute. As you may expect, changes to
786 the foreign key aren't saved to the database until you call ``save()``.
787 Example::
789     >>> e = Entry.objects.get(id=2)
790     >>> e.blog = some_blog
791     >>> e.save()
793 If a ``ForeignKey`` field has ``null=True`` set (i.e., it allows ``NULL``
794 values), you can assign ``None`` to it. Example::
796     >>> e = Entry.objects.get(id=2)
797     >>> e.blog = None
798     >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
800 Forward access to one-to-many relationships is cached the first time the
801 related object is accessed. Subsequent accesses to the foreign key on the same
802 object instance are cached. Example::
804     >>> e = Entry.objects.get(id=2)
805     >>> print e.blog  # Hits the database to retrieve the associated Blog.
806     >>> print e.blog  # Doesn't hit the database; uses cached version.
808 Note that the ``select_related()`` ``QuerySet`` method recursively prepopulates
809 the cache of all one-to-many relationships ahead of time. Example::
811     >>> e = Entry.objects.select_related().get(id=2)
812     >>> print e.blog  # Doesn't hit the database; uses cached version.
813     >>> print e.blog  # Doesn't hit the database; uses cached version.
815 .. _backwards-related-objects:
817 Following relationships "backward"
818 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
820 If a model has a ``ForeignKey``, instances of the foreign-key model will have
821 access to a ``Manager`` that returns all instances of the first model. By
822 default, this ``Manager`` is named ``FOO_set``, where ``FOO`` is the source
823 model name, lowercased. This ``Manager`` returns ``QuerySets``, which can be
824 filtered and manipulated as described in the "Retrieving objects" section
825 above.
827 Example::
829     >>> b = Blog.objects.get(id=1)
830     >>> b.entry_set.all() # Returns all Entry objects related to Blog.
832     # b.entry_set is a Manager that returns QuerySets.
833     >>> b.entry_set.filter(headline__contains='Lennon')
834     >>> b.entry_set.count()
836 You can override the ``FOO_set`` name by setting the ``related_name``
837 parameter in the ``ForeignKey()`` definition. For example, if the ``Entry``
838 model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the
839 above example code would look like this::
841     >>> b = Blog.objects.get(id=1)
842     >>> b.entries.all() # Returns all Entry objects related to Blog.
844     # b.entries is a Manager that returns QuerySets.
845     >>> b.entries.filter(headline__contains='Lennon')
846     >>> b.entries.count()
848 You cannot access a reverse ``ForeignKey`` ``Manager`` from the class; it must
849 be accessed from an instance::
851     >>> Blog.entry_set
852     Traceback:
853         ...
854     AttributeError: "Manager must be accessed via instance".
856 In addition to the ``QuerySet`` methods defined in "Retrieving objects" above,
857 the ``ForeignKey`` ``Manager`` has additional methods used to handle the set of
858 related objects. A synopsis of each is below, and complete details can be found
859 in the :ref:`related objects reference <ref-models-relations>`.
861 ``add(obj1, obj2, ...)``
862     Adds the specified model objects to the related object set.
864 ``create(**kwargs)``
865     Creates a new object, saves it and puts it in the related object set.
866     Returns the newly created object.
868 ``remove(obj1, obj2, ...)``
869     Removes the specified model objects from the related object set.
871 ``clear()``
872     Removes all objects from the related object set.
874 To assign the members of a related set in one fell swoop, just assign to it
875 from any iterable object. Example::
877     b = Blog.objects.get(id=1)
878     b.entry_set = [e1, e2]
880 If the ``clear()`` method is available, any pre-existing objects will be
881 removed from the ``entry_set`` before all objects in the iterable (in this
882 case, a list) are added to the set. If the ``clear()`` method is *not*
883 available, all objects in the iterable will be added without removing any
884 existing elements.
886 Each "reverse" operation described in this section has an immediate effect on
887 the database. Every addition, creation and deletion is immediately and
888 automatically saved to the database.
890 Many-to-many relationships
891 --------------------------
893 Both ends of a many-to-many relationship get automatic API access to the other
894 end. The API works just as a "backward" one-to-many relationship, above.
896 The only difference is in the attribute naming: The model that defines the
897 ``ManyToManyField`` uses the attribute name of that field itself, whereas the
898 "reverse" model uses the lowercased model name of the original model, plus
899 ``'_set'`` (just like reverse one-to-many relationships).
901 An example makes this easier to understand::
903     e = Entry.objects.get(id=3)
904     e.authors.all() # Returns all Author objects for this Entry.
905     e.authors.count()
906     e.authors.filter(name__contains='John')
908     a = Author.objects.get(id=5)
909     a.entry_set.all() # Returns all Entry objects for this Author.
911 Like ``ForeignKey``, ``ManyToManyField`` can specify ``related_name``. In the
912 above example, if the ``ManyToManyField`` in ``Entry`` had specified
913 ``related_name='entries'``, then each ``Author`` instance would have an
914 ``entries`` attribute instead of ``entry_set``.
916 One-to-one relationships
917 ------------------------
919 One-to-one relationships are very similar to many-to-one relationships. If you
920 define a :class:`~django.db.models.OneToOneField` on your model, instances of
921 that model will have access to the related object via a simple attribute of the
922 model.
924 For example::
926     class EntryDetail(models.Model):
927         entry = models.OneToOneField(Entry)
928         details = models.TextField()
930     ed = EntryDetail.objects.get(id=2)
931     ed.entry # Returns the related Entry object.
933 The difference comes in "reverse" queries. The related model in a one-to-one
934 relationship also has access to a :class:`~django.db.models.Manager` object, but
935 that :class:`~django.db.models.Manager` represents a single object, rather than
936 a collection of objects::
938     e = Entry.objects.get(id=2)
939     e.entrydetail # returns the related EntryDetail object
941 If no object has been assigned to this relationship, Django will raise
942 a ``DoesNotExist`` exception.
944 Instances can be assigned to the reverse relationship in the same way as
945 you would assign the forward relationship::
947     e.entrydetail = ed
949 How are the backward relationships possible?
950 --------------------------------------------
952 Other object-relational mappers require you to define relationships on both
953 sides. The Django developers believe this is a violation of the DRY (Don't
954 Repeat Yourself) principle, so Django only requires you to define the
955 relationship on one end.
957 But how is this possible, given that a model class doesn't know which other
958 model classes are related to it until those other model classes are loaded?
960 The answer lies in the :setting:`INSTALLED_APPS` setting. The first time any model is
961 loaded, Django iterates over every model in :setting:`INSTALLED_APPS` and creates the
962 backward relationships in memory as needed. Essentially, one of the functions
963 of :setting:`INSTALLED_APPS` is to tell Django the entire model domain.
965 Queries over related objects
966 ----------------------------
968 Queries involving related objects follow the same rules as queries involving
969 normal value fields. When specifying the value for a query to match, you may
970 use either an object instance itself, or the primary key value for the object.
972 For example, if you have a Blog object ``b`` with ``id=5``, the following
973 three queries would be identical::
975     Entry.objects.filter(blog=b) # Query using object instance
976     Entry.objects.filter(blog=b.id) # Query using id from instance
977     Entry.objects.filter(blog=5) # Query using id directly
979 Falling back to raw SQL
980 =======================
982 If you find yourself needing to write an SQL query that is too complex for
983 Django's database-mapper to handle, you can fall back into raw-SQL statement
984 mode.
986 The preferred way to do this is by giving your model custom methods or custom
987 manager methods that execute queries. Although there's nothing in Django that
988 *requires* database queries to live in the model layer, this approach keeps all
989 your data-access logic in one place, which is smart from an code-organization
990 standpoint. For instructions, see :ref:`topics-db-sql`.
992 Finally, it's important to note that the Django database layer is merely an
993 interface to your database. You can access your database via other tools,
994 programming languages or database frameworks; there's nothing Django-specific
995 about your database.