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.
9 .. _`data models`: ../model-api/
11 Throughout this reference, we'll refer to the following models, which comprise
12 a weblog application::
14 class Blog(models.Model):
15 name = models.CharField(max_length=100)
16 tagline = models.TextField()
18 def __unicode__(self):
21 class Author(models.Model):
22 name = models.CharField(max_length=50)
23 email = models.EmailField()
25 def __unicode__(self):
28 class Entry(models.Model):
29 blog = models.ForeignKey(Blog)
30 headline = models.CharField(max_length=255)
31 body_text = models.TextField()
32 pub_date = models.DateTimeField()
33 authors = models.ManyToManyField(Author)
35 def __unicode__(self):
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.
45 To create an object, instantiate it using keyword arguments to the model class,
46 then call ``save()`` to save it to the database.
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.)
52 Assuming models live in a file ``mysite/blog/models.py``, here's an example::
54 from mysite.blog.models import Blog
55 b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
58 This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
59 the database until you explicitly call ``save()``.
61 The ``save()`` method has no return value.
63 To create an object and save it all in one step see the `create`__ method.
65 __ `create(**kwargs)`_
67 Auto-incrementing primary keys
68 ------------------------------
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()``.
76 b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
77 b2.id # Returns None, because b doesn't have an ID yet.
79 b2.id # Returns the ID of your new object.
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.
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`_.)
88 .. _AutoField documentation: ../model-api/#autofield
90 Explicitly specifying auto-primary-key values
91 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
99 b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
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.
109 Given the above ``'Cheddar Talk'`` blog example, this example would override
110 the previous record in the database::
112 b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
113 b4.save() # Overrides the previous blog with ID=3!
115 See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this
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.
121 What happens when you save?
122 ---------------------------
124 When you save an object, Django performs the following steps:
126 1. **Emit a ``pre_save`` signal.** This provides a notification that
127 an object is about to be saved. You can register a listener that
128 will be invoked whenever this signal is emitted. (These signals are
131 2. **Pre-process the data.** Each field on the object is asked to
132 perform any automated data modification that the field may need
135 Most fields do *no* pre-processing -- the field data is kept as-is.
136 Pre-processing is only used on fields that have special behavior.
137 For example, if your model has a ``DateField`` with ``auto_now=True``,
138 the pre-save phase will alter the data in the object to ensure that
139 the date field contains the current date stamp. (Our documentation
140 doesn't yet include a list of all the fields with this "special
143 3. **Prepare the data for the database.** Each field is asked to provide
144 its current value in a data type that can be written to the database.
146 Most fields require *no* data preparation. Simple data types, such as
147 integers and strings, are 'ready to write' as a Python object. However,
148 more complex data types often require some modification.
150 For example, ``DateFields`` use a Python ``datetime`` object to store
151 data. Databases don't store ``datetime`` objects, so the field value
152 must be converted into an ISO-compliant date string for insertion
155 4. **Insert the data into the database.** The pre-processed, prepared
156 data is then composed into an SQL statement for insertion into the
159 5. **Emit a ``post_save`` signal.** As with the ``pre_save`` signal, this
160 is used to provide notification that an object has been successfully
161 saved. (These signals are not yet documented.)
163 Saving changes to objects
164 =========================
166 To save changes to an object that's already in the database, use ``save()``.
168 Given a ``Blog`` instance ``b5`` that has already been saved to the database,
169 this example changes its name and updates its record in the database::
174 This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
175 the database until you explicitly call ``save()``.
177 The ``save()`` method has no return value.
179 Saving ForeignKey and ManyToManyField fields
180 --------------------------------------------
182 Updating ``ForeignKey`` fields works exactly the same way as saving a normal
183 field; simply assign an object of the right type to the field in question::
185 cheese_blog = Blog.objects.get(name="Cheddar Talk")
186 entry.blog = cheese_blog
189 Updating a ``ManyToManyField`` works a little differently; use the ``add()``
190 method on the field to add a record to the relation::
192 joe = Author.objects.create(name="Joe")
193 entry.authors.add(joe)
195 Django will complain if you try to assign or add an object of the wrong type.
197 How Django knows to UPDATE vs. INSERT
198 -------------------------------------
200 You may have noticed Django database objects use the same ``save()`` method
201 for creating and changing objects. Django abstracts the need to use ``INSERT``
202 or ``UPDATE`` SQL statements. Specifically, when you call ``save()``, Django
203 follows this algorithm:
205 * If the object's primary key attribute is set to a value that evaluates to
206 ``True`` (i.e., a value other than ``None`` or the empty string), Django
207 executes a ``SELECT`` query to determine whether a record with the given
208 primary key already exists.
209 * If the record with the given primary key does already exist, Django
210 executes an ``UPDATE`` query.
211 * If the object's primary key attribute is *not* set, or if it's set but a
212 record doesn't exist, Django executes an ``INSERT``.
214 The one gotcha here is that you should be careful not to specify a primary-key
215 value explicitly when saving new objects, if you cannot guarantee the
216 primary-key value is unused. For more on this nuance, see
217 "Explicitly specifying auto-primary-key values" above.
222 To retrieve objects from your database, you construct a ``QuerySet`` via a
223 ``Manager`` on your model class.
225 A ``QuerySet`` represents a collection of objects from your database. It can
226 have zero, one or many *filters* -- criteria that narrow down the collection
227 based on given parameters. In SQL terms, a ``QuerySet`` equates to a ``SELECT``
228 statement, and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
230 You get a ``QuerySet`` by using your model's ``Manager``. Each model has at
231 least one ``Manager``, and it's called ``objects`` by default. Access it
232 directly via the model class, like so::
234 Blog.objects # <django.db.models.manager.Manager object at ...>
235 b = Blog(name='Foo', tagline='Bar')
236 b.objects # AttributeError: "Manager isn't accessible via Blog instances."
238 (``Managers`` are accessible only via model classes, rather than from model
239 instances, to enforce a separation between "table-level" operations and
240 "record-level" operations.)
242 The ``Manager`` is the main source of ``QuerySets`` for a model. It acts as a
243 "root" ``QuerySet`` that describes all objects in the model's database table.
244 For example, ``Blog.objects`` is the initial ``QuerySet`` that contains all
245 ``Blog`` objects in the database.
247 Retrieving all objects
248 ----------------------
250 The simplest way to retrieve objects from a table is to get all of them.
251 To do this, use the ``all()`` method on a ``Manager``.
255 all_entries = Entry.objects.all()
257 The ``all()`` method returns a ``QuerySet`` of all the objects in the database.
259 (If ``Entry.objects`` is a ``QuerySet``, why can't we just do ``Entry.objects``?
260 That's because ``Entry.objects``, the root ``QuerySet``, is a special case
261 that cannot be evaluated. The ``all()`` method returns a ``QuerySet`` that
267 The root ``QuerySet`` provided by the ``Manager`` describes all objects in the
268 database table. Usually, though, you'll need to select only a subset of the
269 complete set of objects.
271 To create such a subset, you refine the initial ``QuerySet``, adding filter
272 conditions. The two most common ways to refine a ``QuerySet`` are:
275 Returns a new ``QuerySet`` containing objects that match the given lookup
278 ``exclude(**kwargs)``
279 Returns a new ``QuerySet`` containing objects that do *not* match the given
282 The lookup parameters (``**kwargs`` in the above function definitions) should
283 be in the format described in `Field lookups`_ below.
285 For example, to get a ``QuerySet`` of blog entries from the year 2006, use
286 ``filter()`` like so::
288 Entry.objects.filter(pub_date__year=2006)
290 (Note we don't have to add an ``all()`` -- ``Entry.objects.all().filter(...)``.
291 That would still work, but you only need ``all()`` when you want all objects
292 from the root ``QuerySet``.)
297 The result of refining a ``QuerySet`` is itself a ``QuerySet``, so it's
298 possible to chain refinements together. For example::
300 Entry.objects.filter(
301 headline__startswith='What').exclude(
302 pub_date__gte=datetime.now()).filter(
303 pub_date__gte=datetime(2005, 1, 1))
305 ...takes the initial ``QuerySet`` of all entries in the database, adds a
306 filter, then an exclusion, then another filter. The final result is a
307 ``QuerySet`` containing all entries with a headline that starts with "What",
308 that were published between January 1, 2005, and the current day.
310 Filtered QuerySets are unique
311 -----------------------------
313 Each time you refine a ``QuerySet``, you get a brand-new ``QuerySet`` that is
314 in no way bound to the previous ``QuerySet``. Each refinement creates a
315 separate and distinct ``QuerySet`` that can be stored, used and reused.
319 q1 = Entry.objects.filter(headline__startswith="What")
320 q2 = q1.exclude(pub_date__gte=datetime.now())
321 q3 = q1.filter(pub_date__gte=datetime.now())
323 These three ``QuerySets`` are separate. The first is a base ``QuerySet``
324 containing all entries that contain a headline starting with "What". The second
325 is a subset of the first, with an additional criteria that excludes records
326 whose ``pub_date`` is greater than now. The third is a subset of the first,
327 with an additional criteria that selects only the records whose ``pub_date`` is
328 greater than now. The initial ``QuerySet`` (``q1``) is unaffected by the
334 ``QuerySets`` are lazy -- the act of creating a ``QuerySet`` doesn't involve
335 any database activity. You can stack filters together all day long, and Django
336 won't actually run the query until the ``QuerySet`` is *evaluated*.
338 When QuerySets are evaluated
339 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
341 You can evaluate a ``QuerySet`` in the following ways:
343 * **Iteration.** A ``QuerySet`` is iterable, and it executes its database
344 query the first time you iterate over it. For example, this will print
345 the headline of all entries in the database::
347 for e in Entry.objects.all():
350 * **Slicing.** As explained in `Limiting QuerySets`_ below, a ``QuerySet``
351 can be sliced, using Python's array-slicing syntax. Usually slicing a
352 ``QuerySet`` returns another (unevaluated )``QuerySet``, but Django will
353 execute the database query if you use the "step" parameter of slice
356 * **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
357 This is for convenience in the Python interactive interpreter, so you can
358 immediately see your results when using the API interactively.
360 * **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
361 This, as you might expect, returns the length of the result list.
363 Note: *Don't* use ``len()`` on ``QuerySet``\s if all you want to do is
364 determine the number of records in the set. It's much more efficient to
365 handle a count at the database level, using SQL's ``SELECT COUNT(*)``,
366 and Django provides a ``count()`` method for precisely this reason. See
369 * **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
372 entry_list = list(Entry.objects.all())
374 Be warned, though, that this could have a large memory overhead, because
375 Django will load each element of the list into memory. In contrast,
376 iterating over a ``QuerySet`` will take advantage of your database to
377 load data and instantiate objects only as you need them.
383 If you pickle_ a ``QuerySet``, this will also force all the results to be
384 loaded into memory prior to pickling. This is because pickling is usually used
385 as a precursor to caching and when the cached ``QuerySet`` is reloaded, you want
386 the results to already be present. This means that when you unpickle a
387 ``QuerySet``, it contains the results at the moment it was pickled, rather
388 than the results that are currently in the database.
390 If you only want to pickle the necessary information to recreate the
391 ``Queryset`` from the database at a later time, pickle the ``query`` attribute
392 of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
393 any results loaded) using some code like this::
396 >>> query = pickle.loads(s) # Assuming 's' is the pickled string.
397 >>> qs = MyModel.objects.all()
398 >>> qs.query = query # Restore the original 'query'.
400 .. _pickle: http://docs.python.org/lib/module-pickle.html
405 Use Python's array-slicing syntax to limit your ``QuerySet`` to a certain
406 number of results. This is the equivalent of SQL's ``LIMIT`` and ``OFFSET``
409 For example, this returns the first 5 objects (``LIMIT 5``)::
411 Entry.objects.all()[:5]
413 This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::
415 Entry.objects.all()[5:10]
417 You can also slice from the item ''N'' to the end of the queryset. For
418 example, to return everything from the sixth item onwards::
420 Entry.objects.all()[5:]
422 How this last example is implemented in SQL varies depending upon the database
423 used, but it is supported in all cases.
425 Generally, slicing a ``QuerySet`` returns a new ``QuerySet`` -- it doesn't
426 evaluate the query. An exception is if you use the "step" parameter of Python
427 slice syntax. For example, this would actually execute the query in order to
428 return a list of every *second* object of the first 10::
430 Entry.objects.all()[:10:2]
432 To retrieve a *single* object rather than a list
433 (e.g. ``SELECT foo FROM bar LIMIT 1``), use a simple index instead of a
434 slice. For example, this returns the first ``Entry`` in the database, after
435 ordering entries alphabetically by headline::
437 Entry.objects.order_by('headline')[0]
439 This is roughly equivalent to::
441 Entry.objects.order_by('headline')[0:1].get()
443 Note, however, that the first of these will raise ``IndexError`` while the
444 second will raise ``DoesNotExist`` if no objects match the given criteria.
449 If you have two ``QuerySet`` instances that act on the same model, you can
450 combine them using ``&`` and ``|`` to get the items that are in both result
451 sets or in either results set, respectively. For example::
453 Entry.objects.filter(pubdate__gte=date1) & \
454 Entry.objects.filter(headline__startswith="What")
456 will combine the two queries into a single SQL query. Of course, in this case
457 you could have achieved the same result using multiple filters on the same
458 ``QuerySet``, but sometimes the ability to combine individual ``QuerySet``
461 Be careful, if you are using ``extra()`` to add custom handling to your
462 ``QuerySet`` however. All the ``extra()`` components are merged and the result
463 may or may not make sense. If you are using custom SQL fragments in your
464 ``extra()`` calls, Django will not inspect these fragments to see if they need
465 to be rewritten because of changes in the merged query. So test the effects
466 carefully. Also realise that if you are combining two ``QuerySets`` with
467 ``|``, you cannot use ``extra(select=...)`` or ``extra(where=...)`` on *both*
468 ``QuerySets``. You can only use those calls on one or the other (Django will
469 raise a ``ValueError`` if you try to use this incorrectly).
471 QuerySet methods that return new QuerySets
472 ------------------------------------------
474 Django provides a range of ``QuerySet`` refinement methods that modify either
475 the types of results returned by the ``QuerySet`` or the way its SQL query is
481 Returns a new ``QuerySet`` containing objects that match the given lookup
484 The lookup parameters (``**kwargs``) should be in the format described in
485 `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
486 underlying SQL statement.
488 ``exclude(**kwargs)``
489 ~~~~~~~~~~~~~~~~~~~~~
491 Returns a new ``QuerySet`` containing objects that do *not* match the given
494 The lookup parameters (``**kwargs``) should be in the format described in
495 `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
496 underlying SQL statement, and the whole thing is enclosed in a ``NOT()``.
498 This example excludes all entries whose ``pub_date`` is later than 2005-1-3
499 AND whose ``headline`` is "Hello"::
501 Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
503 In SQL terms, that evaluates to::
506 WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
508 This example excludes all entries whose ``pub_date`` is later than 2005-1-3
509 OR whose headline is "Hello"::
511 Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
513 In SQL terms, that evaluates to::
516 WHERE NOT pub_date > '2005-1-3'
517 AND NOT headline = 'Hello'
519 Note the second example is more restrictive.
521 ``order_by(*fields)``
522 ~~~~~~~~~~~~~~~~~~~~~
524 By default, results returned by a ``QuerySet`` are ordered by the ordering
525 tuple given by the ``ordering`` option in the model's ``Meta``. You can
526 override this on a per-``QuerySet`` basis by using the ``order_by`` method.
530 Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
532 The result above will be ordered by ``pub_date`` descending, then by
533 ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
534 *descending* order. Ascending order is implied. To order randomly, use ``"?"``,
537 Entry.objects.order_by('?')
539 Note: ``order_by('?')`` queries may be expensive and slow, depending on the
540 database backend you're using.
542 To order by a field in a different model, use the same syntax as when you are
543 querying across model relations. That is, the name of the field, followed by a
544 double underscore (``__``), followed by the name of the field in the new model,
545 and so on for as many models as you want to join. For example::
547 Entry.objects.order_by('blog__name', 'headline')
549 If you try to order by a field that is a relation to another model, Django will
550 use the default ordering on the related model (or order by the related model's
551 primary key if there is no ``Meta.ordering`` specified. For example::
553 Entry.objects.order_by('blog')
557 Entry.objects.order_by('blog__id')
559 ...since the ``Blog`` model has no default ordering specified.
561 Be cautious when ordering by fields in related models if you are also using
562 ``distinct()``. See the note in the `distinct()`_ section for an explanation
563 of how related model ordering can change the expected results.
565 It is permissible to specify a multi-valued field to order the results by (for
566 example, a ``ManyToMany`` field). Normally this won't be a sensible thing to
567 do and it's really an advanced usage feature. However, if you know that your
568 queryset's filtering or available data implies that there will only be one
569 ordering piece of data for each of the main items you are selecting, the
570 ordering may well be exactly what you want to do. Use ordering on multi-valued
571 fields with care and make sure the results are what you expect.
573 **New in Django development version:** If you don't want any ordering to be
574 applied to a query, not even the default ordering, call ``order_by()`` with no
577 **New in Django development version:** The syntax for ordering across related
578 models has changed. See the `Django 0.96 documentation`_ for the old behavior.
580 .. _Django 0.96 documentation: http://www.djangoproject.com/documentation/0.96/model-api/#floatfield
582 There's no way to specify whether ordering should be case sensitive. With
583 respect to case-sensitivity, Django will order results however your database
584 backend normally orders them.
589 **New in Django development version**
591 Use the ``reverse()`` method to reverse the order in which a queryset's
592 elements are returned. Calling ``reverse()`` a second time restores the
593 ordering back to the normal direction.
595 To retrieve the ''last'' five items in a queryset, you could do this::
597 my_queryset.reverse()[:5]
599 Note that this is not quite the same as slicing from the end of a sequence in
600 Python. The above example will return the last item first, then the
601 penultimate item and so on. If we had a Python sequence and looked at
602 ``seq[:-5]``, we would see the fifth-last item first. Django doesn't support
603 that mode of access (slicing from the end), because it's not possible to do it
609 Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
610 eliminates duplicate rows from the query results.
612 By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
613 is rarely a problem, because simple queries such as ``Blog.objects.all()``
614 don't introduce the possibility of duplicate result rows. However, if your
615 query spans multiple tables, it's possible to get duplicate results when a
616 ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
619 Any fields used in an ``order_by()`` call are included in the SQL
620 ``SELECT`` columns. This can sometimes lead to unexpected results when
621 used in conjunction with ``distinct()``. If you order by fields from a
622 related model, those fields will be added to the selected columns and they
623 may make otherwise duplicate rows appear to be distinct. Since the extra
624 columns don't appear in the returned results (they are only there to
625 support ordering), it sometimes looks like non-distinct results are being
628 Similarly, if you use a ``values()`` query to restrict the columns
629 selected, the columns used in any ``order_by()`` (or default model
630 ordering) will still be involved and may affect uniqueness of the results.
632 The moral here is that if you are using ``distinct()`` be careful about
633 ordering by related models. Similarly, when using ``distinct()`` and
634 ``values()`` together, be careful when ordering by fields not in the
640 Returns a ``ValuesQuerySet`` -- a ``QuerySet`` that evaluates to a list of
641 dictionaries instead of model-instance objects.
643 Each of those dictionaries represents an object, with the keys corresponding to
644 the attribute names of model objects.
646 This example compares the dictionaries of ``values()`` with the normal model
649 # This list contains a Blog object.
650 >>> Blog.objects.filter(name__startswith='Beatles')
653 # This list contains a dictionary.
654 >>> Blog.objects.filter(name__startswith='Beatles').values()
655 [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
657 ``values()`` takes optional positional arguments, ``*fields``, which specify
658 field names to which the ``SELECT`` should be limited. If you specify the
659 fields, each dictionary will contain only the field keys/values for the fields
660 you specify. If you don't specify the fields, each dictionary will contain a
661 key and value for every field in the database table.
665 >>> Blog.objects.values()
666 [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
667 >>> Blog.objects.values('id', 'name')
668 [{'id': 1, 'name': 'Beatles Blog'}]
670 You can also retrieve values from across ``ForeignKey`` relations by using
671 double underscores to separate the field names, just as when calling the
672 ``filter()`` command. For example::
674 >>> Entry.objects.values('blog__name').distinct()
675 [{'name': 'Beatles Blog'}]
677 A couple of subtleties that are worth mentioning:
679 * The ``values()`` method does not return anything for ``ManyToManyField``
680 attributes and will raise an error if you try to pass in this type of
682 * If you have a field called ``foo`` that is a ``ForeignKey``, the default
683 ``values()`` call will return a dictionary key called ``foo_id``, since
684 this is the name of the hidden model attribute that stores the actual
685 value (the ``foo`` attribute refers to the related model). When you are
686 calling ``values()`` and passing in field names, you can pass in either
687 ``foo`` or ``foo_id`` and you will get back the same thing (the
688 dictionary key will match the field name you passed in).
692 >>> Entry.objects.values()
693 [{'blog_id: 1, 'headline': u'First Entry', ...}, ...]
695 >>> Entry.objects.values('blog')
698 >>> Entry.objects.values('blog_id')
699 [{'blog_id': 1}, ...]
700 * When using ``values()`` together with ``distinct()``, be aware that
701 ordering can affect the results. See the note in the `distinct()`_
702 section, above, for details.
704 **New in Django development version:** Previously, it was not possible to pass
705 ``blog_id`` to ``values()`` in the above example, only ``blog``.
707 A ``ValuesQuerySet`` is useful when you know you're only going to need values
708 from a small number of the available fields and you won't need the
709 functionality of a model instance object. It's more efficient to select only
710 the fields you need to use.
712 Finally, note a ``ValuesQuerySet`` is a subclass of ``QuerySet``, so it has all
713 methods of ``QuerySet``. You can call ``filter()`` on it, or ``order_by()``, or
714 whatever. Yes, that means these two calls are identical::
716 Blog.objects.values().order_by('id')
717 Blog.objects.order_by('id').values()
719 The people who made Django prefer to put all the SQL-affecting methods first,
720 followed (optionally) by any output-affecting methods (such as ``values()``),
721 but it doesn't really matter. This is your chance to really flaunt your
724 ``values_list(*fields)``
725 ~~~~~~~~~~~~~~~~~~~~~~~~
727 **New in Django development version**
729 This is similar to ``values()`` except that instead of returning a list of
730 dictionaries, it returns a list of tuples. Each tuple contains the value from
731 the respective field passed into the ``values_list()`` call -- so the first
732 item is the first field, etc. For example::
734 >>> Entry.objects.values_list('id', 'headline')
735 [(1, u'First entry'), ...]
737 If you only pass in a single field, you can also pass in the ``flat``
738 parameter. If ``True``, this will mean the returned results are single values,
739 rather than one-tuples. An example should make the difference clearer::
741 >>> Entry.objects.values_list('id').order_by('id')
742 [(1,), (2,), (3,), ...]
744 >>> Entry.objects.values_list('id', flat=True).order_by('id')
747 It is an error to pass in ``flat`` when there is more than one field.
749 If you don't pass any values to ``values_list()``, it will return all the
750 fields in the model, in the order they were declared.
752 ``dates(field, kind, order='ASC')``
753 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
755 Returns a ``DateQuerySet`` -- a ``QuerySet`` that evaluates to a list of
756 ``datetime.datetime`` objects representing all available dates of a particular
757 kind within the contents of the ``QuerySet``.
759 ``field`` should be the name of a ``DateField`` or ``DateTimeField`` of your
762 ``kind`` should be either ``"year"``, ``"month"`` or ``"day"``. Each
763 ``datetime.datetime`` object in the result list is "truncated" to the given
766 * ``"year"`` returns a list of all distinct year values for the field.
767 * ``"month"`` returns a list of all distinct year/month values for the field.
768 * ``"day"`` returns a list of all distinct year/month/day values for the field.
770 ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
771 ``'DESC'``. This specifies how to order the results.
775 >>> Entry.objects.dates('pub_date', 'year')
776 [datetime.datetime(2005, 1, 1)]
777 >>> Entry.objects.dates('pub_date', 'month')
778 [datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
779 >>> Entry.objects.dates('pub_date', 'day')
780 [datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
781 >>> Entry.objects.dates('pub_date', 'day', order='DESC')
782 [datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)]
783 >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
784 [datetime.datetime(2005, 3, 20)]
789 **New in Django development version**
791 Returns an ``EmptyQuerySet`` -- a ``QuerySet`` that always evaluates to
792 an empty list. This can be used in cases where you know that you should
793 return an empty result set and your caller is expecting a ``QuerySet``
794 object (instead of returning an empty list, for example.)
798 >>> Entry.objects.none()
804 **New in Django development version**
806 Returns a ''copy'' of the current ``QuerySet`` (or ``QuerySet`` subclass you
807 pass in). This can be useful in some situations where you might want to pass
808 in either a model manager or a ``QuerySet`` and do further filtering on the
809 result. You can safely call ``all()`` on either object and then you'll
810 definitely have a ``QuerySet`` to work with.
815 Returns a ``QuerySet`` that will automatically "follow" foreign-key
816 relationships, selecting that additional related-object data when it executes
817 its query. This is a performance booster which results in (sometimes much)
818 larger queries but means later use of foreign-key relationships won't require
821 The following examples illustrate the difference between plain lookups and
822 ``select_related()`` lookups. Here's standard lookup::
825 e = Entry.objects.get(id=5)
827 # Hits the database again to get the related Blog object.
830 And here's ``select_related`` lookup::
833 e = Entry.objects.select_related().get(id=5)
835 # Doesn't hit the database, because e.blog has been prepopulated
836 # in the previous query.
839 ``select_related()`` follows foreign keys as far as possible. If you have the
842 class City(models.Model):
845 class Person(models.Model):
847 hometown = models.ForeignKey(City)
849 class Book(models.Model):
851 author = models.ForeignKey(Person)
853 ...then a call to ``Book.objects.select_related().get(id=4)`` will cache the
854 related ``Person`` *and* the related ``City``::
856 b = Book.objects.select_related().get(id=4)
857 p = b.author # Doesn't hit the database.
858 c = p.hometown # Doesn't hit the database.
860 b = Book.objects.get(id=4) # No select_related() in this example.
861 p = b.author # Hits the database.
862 c = p.hometown # Hits the database.
864 Note that, by default, ``select_related()`` does not follow foreign keys that
867 Usually, using ``select_related()`` can vastly improve performance because your
868 app can avoid many database calls. However, in situations with deeply nested
869 sets of relationships ``select_related()`` can sometimes end up following "too
870 many" relations, and can generate queries so large that they end up being slow.
872 In these situations, you can use the ``depth`` argument to ``select_related()``
873 to control how many "levels" of relations ``select_related()`` will actually
876 b = Book.objects.select_related(depth=1).get(id=4)
877 p = b.author # Doesn't hit the database.
878 c = p.hometown # Requires a database call.
880 The ``depth`` argument is new in the Django development version.
882 **New in Django development version:** Sometimes you only need to access
883 specific models that are related to your root model, not all of the related
884 models. In these cases, you can pass the related field names to
885 ``select_related()`` and it will only follow those relations. You can even do
886 this for models that are more than one relation away by separating the field
887 names with double underscores, just as for filters. For example, if we have
890 class Room(models.Model):
892 building = models.ForeignKey(...)
894 class Group(models.Model):
896 teacher = models.ForeignKey(...)
897 room = models.ForeignKey(Room)
898 subject = models.ForeignKey(...)
900 ...and we only needed to work with the ``room`` and ``subject`` attributes, we
903 g = Group.objects.select_related('room', 'subject')
907 g = Group.objects.select_related('room__building', 'subject')
909 ...and would also pull in the ``building`` relation.
911 You can only refer to ``ForeignKey`` relations in the list of fields passed to
912 ``select_related``. You *can* refer to foreign keys that have ``null=True``
913 (unlike the default ``select_related()`` call). It's an error to use both a
914 list of fields and the ``depth`` parameter in the same ``select_related()``
915 call, since they are conflicting options.
917 ``extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)``
918 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
920 Sometimes, the Django query syntax by itself can't easily express a complex
921 ``WHERE`` clause. For these edge cases, Django provides the ``extra()``
922 ``QuerySet`` modifier -- a hook for injecting specific clauses into the SQL
923 generated by a ``QuerySet``.
925 By definition, these extra lookups may not be portable to different database
926 engines (because you're explicitly writing SQL code) and violate the DRY
927 principle, so you should avoid them if possible.
929 Specify one or more of ``params``, ``select``, ``where`` or ``tables``. None
930 of the arguments is required, but you should use at least one of them.
933 The ``select`` argument lets you put extra fields in the ``SELECT`` clause.
934 It should be a dictionary mapping attribute names to SQL clauses to use to
935 calculate that attribute.
939 Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
941 As a result, each ``Entry`` object will have an extra attribute,
942 ``is_recent``, a boolean representing whether the entry's ``pub_date`` is
943 greater than Jan. 1, 2006.
945 Django inserts the given SQL snippet directly into the ``SELECT``
946 statement, so the resulting SQL of the above example would be::
948 SELECT blog_entry.*, (pub_date > '2006-01-01')
952 The next example is more advanced; it does a subquery to give each
953 resulting ``Blog`` object an ``entry_count`` attribute, an integer count
954 of associated ``Entry`` objects::
958 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
962 (In this particular case, we're exploiting the fact that the query will
963 already contain the ``blog_blog`` table in its ``FROM`` clause.)
965 The resulting SQL of the above example would be::
967 SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id)
970 Note that the parenthesis required by most database engines around
971 subqueries are not required in Django's ``select`` clauses. Also note that
972 some database backends, such as some MySQL versions, don't support
975 **New in Django development version**
976 In some rare cases, you might wish to pass parameters to the SQL fragments
977 in ``extra(select=...)```. For this purpose, use the ``select_params``
978 parameter. Since ``select_params`` is a sequence and the ``select``
979 attribute is a dictionary, some care is required so that the parameters
980 are matched up correctly with the extra select pieces. In this situation,
981 you should use a ``django.utils.datastructures.SortedDict`` for the
982 ``select`` value, not just a normal Python dictionary.
984 This will work, for example::
987 select=SortedDict(('a', '%s'), ('b', '%s')),
988 select_params=('one', 'two'))
990 ``where`` / ``tables``
991 You can define explicit SQL ``WHERE`` clauses -- perhaps to perform
992 non-explicit joins -- by using ``where``. You can manually add tables to
993 the SQL ``FROM`` clause by using ``tables``.
995 ``where`` and ``tables`` both take a list of strings. All ``where``
996 parameters are "AND"ed to any other search criteria.
1000 Entry.objects.extra(where=['id IN (3, 4, 5, 20)'])
1002 ...translates (roughly) into the following SQL::
1004 SELECT * FROM blog_entry WHERE id IN (3, 4, 5, 20);
1006 Be careful when using the ``tables`` parameter if you're specifying
1007 tables that are already used in the query. When you add extra tables
1008 via the ``tables`` parameter, Django assumes you want that table included
1009 an extra time, if it is already included. That creates a problem,
1010 since the table name will then be given an alias. If a table appears
1011 multiple times in an SQL statement, the second and subsequent occurrences
1012 must use aliases so the database can tell them apart. If you're
1013 referring to the extra table you added in the extra ``where`` parameter
1014 this is going to cause errors.
1016 Normally you'll only be adding extra tables that don't already appear in
1017 the query. However, if the case outlined above does occur, there are a few
1018 solutions. First, see if you can get by without including the extra table
1019 and use the one already in the query. If that isn't possible, put your
1020 ``extra()`` call at the front of the queryset construction so that your
1021 table is the first use of that table. Finally, if all else fails, look at
1022 the query produced and rewrite your ``where`` addition to use the alias
1023 given to your extra table. The alias will be the same each time you
1024 construct the queryset in the same way, so you can rely upon the alias
1028 If you need to order the resulting queryset using some of the new fields
1029 or tables you have included via ``extra()`` use the ``order_by`` parameter
1030 to ``extra()`` and pass in a sequence of strings. These strings should
1031 either be model fields (as in the normal ``order_by()`` method on
1032 querysets), of the form ``table_name.column_name`` or an alias for a column
1033 that you specified in the ``select`` parameter to ``extra()``.
1037 q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
1038 q = q.extra(order_by = ['-is_recent'])
1040 This would sort all the items for which ``is_recent`` is true to the front
1041 of the result set (``True`` sorts before ``False`` in a descending
1044 This shows, by the way, that you can make multiple calls to
1045 ``extra()`` and it will behave as you expect (adding new constraints each
1049 The ``where`` parameter described above may use standard Python database
1050 string placeholders -- ``'%s'`` to indicate parameters the database engine
1051 should automatically quote. The ``params`` argument is a list of any extra
1052 parameters to be substituted.
1056 Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
1058 Always use ``params`` instead of embedding values directly into ``where``
1059 because ``params`` will ensure values are quoted correctly according to
1060 your particular backend. (For example, quotes will be escaped correctly.)
1064 Entry.objects.extra(where=["headline='Lennon'"])
1068 Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
1070 **New in Django development version** The ``select_params`` argument to
1071 ``extra()`` is new. Previously, you could attempt to pass parameters for
1072 ``select`` in the ``params`` argument, but it worked very unreliably.
1074 QuerySet methods that do not return QuerySets
1075 ---------------------------------------------
1077 The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
1078 something *other than* a ``QuerySet``.
1080 These methods do not use a cache (see `Caching and QuerySets`_ below). Rather,
1081 they query the database each time they're called.
1086 Returns the object matching the given lookup parameters, which should be in
1087 the format described in `Field lookups`_.
1089 ``get()`` raises ``MultipleObjectsReturned`` if more than one object was found.
1090 The ``MultipleObjectsReturned`` exception is an attribute of the model class.
1091 For example, the following will raise ``MultipleObjectsReturned`` if there
1092 are more than one authors with the name of 'John'::
1094 Author.objects.get(name='John') # raises Author.MultipleObjectsReturned
1096 ``get()`` raises a ``DoesNotExist`` exception if an object wasn't found for the
1097 given parameters. The ``DoesNotExist`` exception is an attribute of the model
1100 Entry.objects.get(id='foo') # raises Entry.DoesNotExist
1102 The ``DoesNotExist`` exception inherits from
1103 ``django.core.exceptions.ObjectDoesNotExist``, so you can target multiple
1104 ``DoesNotExist`` exceptions. Example::
1106 from django.core.exceptions import ObjectDoesNotExist
1108 e = Entry.objects.get(id=3)
1109 b = Blog.objects.get(id=1)
1110 except ObjectDoesNotExist:
1111 print "Either the entry or blog doesn't exist."
1113 ``create(**kwargs)``
1114 ~~~~~~~~~~~~~~~~~~~~
1116 A convenience method for creating an object and saving it all in one step. Thus::
1118 p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
1122 p = Person(first_name="Bruce", last_name="Springsteen")
1127 ``get_or_create(**kwargs)``
1128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1130 A convenience method for looking up an object with the given kwargs, creating
1133 Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
1134 created object and ``created`` is a boolean specifying whether a new object was
1137 This is meant as a shortcut to boilerplatish code and is mostly useful for
1138 data-import scripts. For example::
1141 obj = Person.objects.get(first_name='John', last_name='Lennon')
1142 except Person.DoesNotExist:
1143 obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
1146 This pattern gets quite unwieldy as the number of fields in a model goes up.
1147 The above example can be rewritten using ``get_or_create()`` like so::
1149 obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
1150 defaults={'birthday': date(1940, 10, 9)})
1152 Any keyword arguments passed to ``get_or_create()`` -- *except* an optional one
1153 called ``defaults`` -- will be used in a ``get()`` call. If an object is found,
1154 ``get_or_create()`` returns a tuple of that object and ``False``. If an object
1155 is *not* found, ``get_or_create()`` will instantiate and save a new object,
1156 returning a tuple of the new object and ``True``. The new object will be
1157 created according to this algorithm::
1159 defaults = kwargs.pop('defaults', {})
1160 params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
1161 params.update(defaults)
1162 obj = self.model(**params)
1165 In English, that means start with any non-``'defaults'`` keyword argument that
1166 doesn't contain a double underscore (which would indicate a non-exact lookup).
1167 Then add the contents of ``defaults``, overriding any keys if necessary, and
1168 use the result as the keyword arguments to the model class.
1170 If you have a field named ``defaults`` and want to use it as an exact lookup in
1171 ``get_or_create()``, just use ``'defaults__exact'``, like so::
1173 Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})
1175 Finally, a word on using ``get_or_create()`` in Django views. As mentioned
1176 earlier, ``get_or_create()`` is mostly useful in scripts that need to parse
1177 data and create new records if existing ones aren't available. But if you need
1178 to use ``get_or_create()`` in a view, please make sure to use it only in
1179 ``POST`` requests unless you have a good reason not to. ``GET`` requests
1180 shouldn't have any effect on data; use ``POST`` whenever a request to a page
1181 has a side effect on your data. For more, see `Safe methods`_ in the HTTP spec.
1183 .. _Safe methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
1188 Returns an integer representing the number of objects in the database matching
1189 the ``QuerySet``. ``count()`` never raises exceptions.
1193 # Returns the total number of entries in the database.
1194 Entry.objects.count()
1196 # Returns the number of entries whose headline contains 'Lennon'
1197 Entry.objects.filter(headline__contains='Lennon').count()
1199 ``count()`` performs a ``SELECT COUNT(*)`` behind the scenes, so you should
1200 always use ``count()`` rather than loading all of the record into Python
1201 objects and calling ``len()`` on the result.
1203 Depending on which database you're using (e.g. PostgreSQL vs. MySQL),
1204 ``count()`` may return a long integer instead of a normal Python integer. This
1205 is an underlying implementation quirk that shouldn't pose any real-world
1208 ``in_bulk(id_list)``
1209 ~~~~~~~~~~~~~~~~~~~~
1211 Takes a list of primary-key values and returns a dictionary mapping each
1212 primary-key value to an instance of the object with the given ID.
1216 >>> Blog.objects.in_bulk([1])
1218 >>> Blog.objects.in_bulk([1, 2])
1219 {1: Beatles Blog, 2: Cheddar Talk}
1220 >>> Blog.objects.in_bulk([])
1223 If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.
1228 Evaluates the ``QuerySet`` (by performing the query) and returns an
1229 `iterator`_ over the results. A ``QuerySet`` typically reads all of
1230 its results and instantiates all of the corresponding objects the
1231 first time you access it; ``iterator()`` will instead read results and
1232 instantiate objects in discrete chunks, yielding them one at a
1233 time. For a ``QuerySet`` which returns a large number of objects, this
1234 often results in better performance and a significant reduction in
1237 Note that using ``iterator()`` on a ``QuerySet`` which has already
1238 been evaluated will force it to evaluate again, repeating the query.
1240 .. _iterator: http://www.python.org/dev/peps/pep-0234/
1242 ``latest(field_name=None)``
1243 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1245 Returns the latest object in the table, by date, using the ``field_name``
1246 provided as the date field.
1248 This example returns the latest ``Entry`` in the table, according to the
1249 ``pub_date`` field::
1251 Entry.objects.latest('pub_date')
1253 If your model's ``Meta`` specifies ``get_latest_by``, you can leave off the
1254 ``field_name`` argument to ``latest()``. Django will use the field specified in
1255 ``get_latest_by`` by default.
1257 Like ``get()``, ``latest()`` raises ``DoesNotExist`` if an object doesn't
1258 exist with the given parameters.
1260 Note ``latest()`` exists purely for convenience and readability.
1265 Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
1266 specified as keyword arguments to the ``QuerySet`` methods ``filter()``,
1267 ``exclude()`` and ``get()``.
1269 Basic lookups keyword arguments take the form ``field__lookuptype=value``.
1270 (That's a double-underscore). For example::
1272 Entry.objects.filter(pub_date__lte='2006-01-01')
1274 translates (roughly) into the following SQL::
1276 SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
1278 .. admonition:: How this is possible
1280 Python has the ability to define functions that accept arbitrary name-value
1281 arguments whose names and values are evaluated at runtime. For more
1282 information, see `Keyword Arguments`_ in the official Python tutorial.
1284 .. _`Keyword Arguments`: http://docs.python.org/tut/node6.html#SECTION006720000000000000000
1286 If you pass an invalid keyword argument, a lookup function will raise
1289 The database API supports the following lookup types:
1294 Exact match. If the value provided for comparison is ``None``, it will
1295 be interpreted as an SQL ``NULL`` (See isnull_ for more details).
1299 Entry.objects.get(id__exact=14)
1300 Entry.objects.get(id__exact=None)
1304 SELECT ... WHERE id = 14;
1305 SELECT ... WHERE id IS NULL;
1307 **New in Django development version:** The semantics of ``id__exact=None`` have
1308 changed in the development version. Previously, it was (intentionally)
1309 converted to ``WHERE id = NULL`` at the SQL level, which would never match
1310 anything. It has now been changed to behave the same as ``id__isnull=True``.
1315 Case-insensitive exact match.
1319 Blog.objects.get(name__iexact='beatles blog')
1323 SELECT ... WHERE name ILIKE 'beatles blog';
1325 Note this will match ``'Beatles Blog'``, ``'beatles blog'``,
1326 ``'BeAtLes BLoG'``, etc.
1331 Case-sensitive containment test.
1335 Entry.objects.get(headline__contains='Lennon')
1339 SELECT ... WHERE headline LIKE '%Lennon%';
1341 Note this will match the headline ``'Today Lennon honored'`` but not
1342 ``'today lennon honored'``.
1344 SQLite doesn't support case-sensitive ``LIKE`` statements; ``contains`` acts
1345 like ``icontains`` for SQLite.
1350 Case-insensitive containment test.
1354 Entry.objects.get(headline__icontains='Lennon')
1358 SELECT ... WHERE headline ILIKE '%Lennon%';
1367 Entry.objects.filter(id__gt=4)
1371 SELECT ... WHERE id > 4;
1376 Greater than or equal to.
1386 Less than or equal to.
1395 Entry.objects.filter(id__in=[1, 3, 4])
1399 SELECT ... WHERE id IN (1, 3, 4);
1401 You can also use a queryset to dynamically evaluate the list of values
1402 instead of providing a list of literal values. The queryset must be
1403 reduced to a list of individual values using the ``values()`` method,
1404 and then converted into a query using the ``query`` attribute::
1406 Entry.objects.filter(blog__in=Blog.objects.filter(name__contains='Cheddar').values('pk').query)
1408 This queryset will be evaluated as subselect statement::
1410 SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%')
1415 Case-sensitive starts-with.
1419 Entry.objects.filter(headline__startswith='Will')
1423 SELECT ... WHERE headline LIKE 'Will%';
1425 SQLite doesn't support case-sensitive ``LIKE`` statements; ``startswith`` acts
1426 like ``istartswith`` for SQLite.
1431 Case-insensitive starts-with.
1435 Entry.objects.filter(headline__istartswith='will')
1439 SELECT ... WHERE headline ILIKE 'Will%';
1444 Case-sensitive ends-with.
1448 Entry.objects.filter(headline__endswith='cats')
1452 SELECT ... WHERE headline LIKE '%cats';
1454 SQLite doesn't support case-sensitive ``LIKE`` statements; ``endswith`` acts
1455 like ``iendswith`` for SQLite.
1460 Case-insensitive ends-with.
1464 Entry.objects.filter(headline__iendswith='will')
1468 SELECT ... WHERE headline ILIKE '%will'
1473 Range test (inclusive).
1477 start_date = datetime.date(2005, 1, 1)
1478 end_date = datetime.date(2005, 3, 31)
1479 Entry.objects.filter(pub_date__range=(start_date, end_date))
1483 SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
1485 You can use ``range`` anywhere you can use ``BETWEEN`` in SQL -- for dates,
1486 numbers and even characters.
1491 For date/datetime fields, exact year match. Takes a four-digit year.
1495 Entry.objects.filter(pub_date__year=2005)
1499 SELECT ... WHERE EXTRACT('year' FROM pub_date) = '2005';
1501 (The exact SQL syntax varies for each database engine.)
1506 For date/datetime fields, exact month match. Takes an integer 1 (January)
1507 through 12 (December).
1511 Entry.objects.filter(pub_date__month=12)
1515 SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';
1517 (The exact SQL syntax varies for each database engine.)
1522 For date/datetime fields, exact day match.
1526 Entry.objects.filter(pub_date__day=3)
1530 SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
1532 (The exact SQL syntax varies for each database engine.)
1534 Note this will match any record with a pub_date on the third day of the month,
1535 such as January 3, July 3, etc.
1540 Takes either ``True`` or ``False``, which correspond to SQL queries of
1541 ``IS NULL`` and ``IS NOT NULL``, respectively.
1545 Entry.objects.filter(pub_date__isnull=True)
1549 SELECT ... WHERE pub_date IS NULL;
1554 A boolean full-text search, taking advantage of full-text indexing. This is
1555 like ``contains`` but is significantly faster due to full-text indexing.
1557 Note this is only available in MySQL and requires direct manipulation of the
1558 database to add the full-text index.
1563 **New in Django development version**
1565 Case-sensitive regular expression match.
1567 The regular expression syntax is that of the database backend in use. In the
1568 case of SQLite, which doesn't natively support regular-expression lookups, the
1569 syntax is that of Python's ``re`` module.
1573 Entry.objects.get(title__regex=r'^(An?|The) +')
1577 SELECT ... WHERE title REGEXP BINARY '^(An?|The) +'; -- MySQL
1579 SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'c'); -- Oracle
1581 SELECT ... WHERE title ~ '^(An?|The) +'; -- PostgreSQL
1583 SELECT ... WHERE title REGEXP '^(An?|The) +'; -- SQLite
1585 Using raw strings (e.g., ``r'foo'`` instead of ``'foo'``) for passing in the
1586 regular expression syntax is recommended.
1591 **New in Django development version**
1593 Case-insensitive regular expression match.
1597 Entry.objects.get(title__iregex=r'^(an?|the) +')
1601 SELECT ... WHERE title REGEXP '^(an?|the) +'; -- MySQL
1603 SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'i'); -- Oracle
1605 SELECT ... WHERE title ~* '^(an?|the) +'; -- PostgreSQL
1607 SELECT ... WHERE title REGEXP '(?i)^(an?|the) +'; -- SQLite
1609 Default lookups are exact
1610 -------------------------
1612 If you don't provide a lookup type -- that is, if your keyword argument doesn't
1613 contain a double underscore -- the lookup type is assumed to be ``exact``.
1615 For example, the following two statements are equivalent::
1617 Blog.objects.get(id__exact=14) # Explicit form
1618 Blog.objects.get(id=14) # __exact is implied
1620 This is for convenience, because ``exact`` lookups are the common case.
1622 The pk lookup shortcut
1623 ----------------------
1625 For convenience, Django provides a ``pk`` lookup type, which stands for
1628 In the example ``Blog`` model, the primary key is the ``id`` field, so these
1629 three statements are equivalent::
1631 Blog.objects.get(id__exact=14) # Explicit form
1632 Blog.objects.get(id=14) # __exact is implied
1633 Blog.objects.get(pk=14) # pk implies id__exact
1635 The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
1636 can be combined with ``pk`` to perform a query on the primary key of a model::
1638 # Get blogs entries with id 1, 4 and 7
1639 Blog.objects.filter(pk__in=[1,4,7])
1640 # Get all blog entries with id > 14
1641 Blog.objects.filter(pk__gt=14)
1643 ``pk`` lookups also work across joins. For example, these three statements are
1646 Entry.objects.filter(blog__id__exact=3) # Explicit form
1647 Entry.objects.filter(blog__id=3) # __exact is implied
1648 Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
1651 Because of this shortcut, you cannot have a field called ``pk`` that is not
1652 the primary key of the model. It will always be replaced by the name of the
1653 model's primary key in queries.
1655 Lookups that span relationships
1656 -------------------------------
1658 Django offers a powerful and intuitive way to "follow" relationships in
1659 lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the
1660 scenes. To span a relationship, just use the field name of related fields
1661 across models, separated by double underscores, until you get to the field you
1664 This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
1665 is ``'Beatles Blog'``::
1667 Entry.objects.filter(blog__name__exact='Beatles Blog')
1669 This spanning can be as deep as you'd like.
1671 It works backwards, too. To refer to a "reverse" relationship, just use the
1672 lowercase name of the model.
1674 This example retrieves all ``Blog`` objects which have at least one ``Entry``
1675 whose ``headline`` contains ``'Lennon'``::
1677 Blog.objects.filter(entry__headline__contains='Lennon')
1679 Spanning multi-valued relationships
1680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1682 **New in Django development version**
1684 When you are filtering an object based on a ``ManyToManyField`` or a reverse
1685 ``ForeignKeyField``, there are two different sorts of filter you may be
1686 interested in. Consider the ``Blog``/``Entry`` relationship (``Blog`` to
1687 ``Entry`` is a one-to-many relation). We might be interested in finding blogs
1688 that have an entry which has both *"Lennon"* in the headline and was published
1689 today. Or we might want to find blogs that have an entry with *"Lennon"* in
1690 the headline as well as an entry that was published today. Since there are
1691 multiple entries associated with a single ``Blog``, both of these queries are
1692 possible and make sense in some situations.
1694 The same type of situation arises with a ``ManyToManyField``. For example, if
1695 an ``Entry`` has a ``ManyToManyField`` called ``tags``, we might want to find
1696 entries linked to tags called *"music"* and *"bands"* or we might want an
1697 entry that contains a tag with a name of *"music"* and a status of *"public"*.
1699 To handle both of these situations, Django has a consistent way of processing
1700 ``filter()`` and ``exclude()`` calls. Everything inside a single ``filter()``
1701 call is applied simultaneously to filter out items matching all those
1702 requirements. Successive ``filter()`` calls further restrict the set of
1703 objects, but for multi-valued relations, they apply to any object linked to
1704 the primary model, not necessarily those objects that were selected by an
1705 earlier ``filter()`` call.
1707 That may sound a bit confusing, so hopefully an example will clarify. To
1708 select all blogs that contains entries with *"Lennon"* in the headline and
1709 were published today, we would write::
1711 Blog.objects.filter(entry__headline__contains='Lennon',
1712 entry__pub_date=datetime.date.today())
1714 To select all blogs that contain an entry with *"Lennon"* in the headline
1715 **as well as** an entry that was published today, we would write::
1717 Blog.objects.filter(entry__headline__contains='Lennon').filter(
1718 entry__pub_date=datetime.date.today())
1720 In this second example, the first filter restricted the queryset to all those
1721 blogs linked to that particular type of entry. The second filter restricted
1722 the set of blogs *further* to those that are also linked to the second type of
1723 entry. The entries select by the second filter may or may not be the same as
1724 the entries in the first filter. We are filtering the ``Blog`` items with each
1725 filter statement, not the ``Entry`` items.
1727 All of this behavior also applies to ``exclude()``: all the conditions in a
1728 single ``exclude()`` statement apply to a single instance (if those conditions
1729 are talking about the same multi-valued relation). Conditions in subsequent
1730 ``filter()`` or ``exclude()`` calls that refer to the same relation may end up
1731 filtering on different linked objects.
1733 Escaping percent signs and underscores in LIKE statements
1734 ---------------------------------------------------------
1736 The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
1737 ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
1738 and ``iendswith``) will automatically escape the two special characters used in
1739 ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
1740 statement, the percent sign signifies a multiple-character wildcard and the
1741 underscore signifies a single-character wildcard.)
1743 This means things should work intuitively, so the abstraction doesn't leak.
1744 For example, to retrieve all the entries that contain a percent sign, just use
1745 the percent sign as any other character::
1747 Entry.objects.filter(headline__contains='%')
1749 Django takes care of the quoting for you; the resulting SQL will look something
1752 SELECT ... WHERE headline LIKE '%\%%';
1754 Same goes for underscores. Both percentage signs and underscores are handled
1755 for you transparently.
1757 Caching and QuerySets
1758 ---------------------
1760 Each ``QuerySet`` contains a cache, to minimize database access. It's important
1761 to understand how it works, in order to write the most efficient code.
1763 In a newly created ``QuerySet``, the cache is empty. The first time a
1764 ``QuerySet`` is evaluated -- and, hence, a database query happens -- Django
1765 saves the query results in the ``QuerySet``'s cache and returns the results
1766 that have been explicitly requested (e.g., the next element, if the
1767 ``QuerySet`` is being iterated over). Subsequent evaluations of the
1768 ``QuerySet`` reuse the cached results.
1770 Keep this caching behavior in mind, because it may bite you if you don't use
1771 your ``QuerySet``\s correctly. For example, the following will create two
1772 ``QuerySet``\s, evaluate them, and throw them away::
1774 print [e.headline for e in Entry.objects.all()]
1775 print [e.pub_date for e in Entry.objects.all()]
1777 That means the same database query will be executed twice, effectively doubling
1778 your database load. Also, there's a possibility the two lists may not include
1779 the same database records, because an ``Entry`` may have been added or deleted
1780 in the split second between the two requests.
1782 To avoid this problem, simply save the ``QuerySet`` and reuse it::
1784 queryset = Poll.objects.all()
1785 print [p.headline for p in queryset] # Evaluate the query set.
1786 print [p.pub_date for p in queryset] # Re-use the cache from the evaluation.
1791 To compare two model instances, just use the standard Python comparison operator,
1792 the double equals sign: ``==``. Behind the scenes, that compares the primary
1793 key values of two models.
1795 Using the ``Entry`` example above, the following two statements are equivalent::
1797 some_entry == other_entry
1798 some_entry.id == other_entry.id
1800 If a model's primary key isn't called ``id``, no problem. Comparisons will
1801 always use the primary key, whatever it's called. For example, if a model's
1802 primary key field is called ``name``, these two statements are equivalent::
1804 some_obj == other_obj
1805 some_obj.name == other_obj.name
1807 Complex lookups with Q objects
1808 ==============================
1810 Keyword argument queries -- in ``filter()``, etc. -- are "AND"ed together. If
1811 you need to execute more complex queries (for example, queries with ``OR``
1812 statements), you can use ``Q`` objects.
1814 A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a
1815 collection of keyword arguments. These keyword arguments are specified as in
1816 "Field lookups" above.
1818 For example, this ``Q`` object encapsulates a single ``LIKE`` query::
1820 Q(question__startswith='What')
1822 ``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
1823 operator is used on two ``Q`` objects, it yields a new ``Q`` object.
1825 For example, this statement yields a single ``Q`` object that represents the
1826 "OR" of two ``"question__startswith"`` queries::
1828 Q(question__startswith='Who') | Q(question__startswith='What')
1830 This is equivalent to the following SQL ``WHERE`` clause::
1832 WHERE question LIKE 'Who%' OR question LIKE 'What%'
1834 You can compose statements of arbitrary complexity by combining ``Q`` objects
1835 with the ``&`` and ``|`` operators. You can also use parenthetical grouping.
1837 **New in Django development version:** ``Q`` objects can also be negated using
1838 the ``~`` operator, allowing for combined lookups that combine both a normal
1839 query and a negated (``NOT``) query::
1841 Q(question__startswith='Who') | ~Q(pub_date__year=2005)
1843 Each lookup function that takes keyword-arguments (e.g. ``filter()``,
1844 ``exclude()``, ``get()``) can also be passed one or more ``Q`` objects as
1845 positional (not-named) arguments. If you provide multiple ``Q`` object
1846 arguments to a lookup function, the arguments will be "AND"ed together. For
1850 Q(question__startswith='Who'),
1851 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
1854 ... roughly translates into the SQL::
1856 SELECT * from polls WHERE question LIKE 'Who%'
1857 AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
1859 Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
1860 arguments provided to a lookup function (be they keyword arguments or ``Q``
1861 objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
1862 precede the definition of any keyword arguments. For example::
1865 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
1866 question__startswith='Who')
1868 ... would be a valid query, equivalent to the previous example; but::
1872 question__startswith='Who',
1873 Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
1875 ... would not be valid.
1877 See the `OR lookups examples page`_ for more examples.
1879 .. _OR lookups examples page: ../models/or_lookups/
1884 When you define a relationship in a model (i.e., a ``ForeignKey``,
1885 ``OneToOneField``, or ``ManyToManyField``), instances of that model will have
1886 a convenient API to access the related object(s).
1888 Using the models at the top of this page, for example, an ``Entry`` object ``e``
1889 can get its associated ``Blog`` object by accessing the ``blog`` attribute:
1892 (Behind the scenes, this functionality is implemented by Python descriptors_.
1893 This shouldn't really matter to you, but we point it out here for the curious.)
1895 Django also creates API accessors for the "other" side of the relationship --
1896 the link from the related model to the model that defines the relationship.
1897 For example, a ``Blog`` object ``b`` has access to a list of all related
1898 ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
1900 All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
1901 models defined at the top of this page.
1903 .. _descriptors: http://users.rcn.com/python/download/Descriptor.htm
1905 One-to-many relationships
1906 -------------------------
1911 If a model has a ``ForeignKey``, instances of that model will have access to
1912 the related (foreign) object via a simple attribute of the model.
1916 e = Entry.objects.get(id=2)
1917 e.blog # Returns the related Blog object.
1919 You can get and set via a foreign-key attribute. As you may expect, changes to
1920 the foreign key aren't saved to the database until you call ``save()``.
1923 e = Entry.objects.get(id=2)
1927 If a ``ForeignKey`` field has ``null=True`` set (i.e., it allows ``NULL``
1928 values), you can assign ``None`` to it. Example::
1930 e = Entry.objects.get(id=2)
1932 e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
1934 Forward access to one-to-many relationships is cached the first time the
1935 related object is accessed. Subsequent accesses to the foreign key on the same
1936 object instance are cached. Example::
1938 e = Entry.objects.get(id=2)
1939 print e.blog # Hits the database to retrieve the associated Blog.
1940 print e.blog # Doesn't hit the database; uses cached version.
1942 Note that the ``select_related()`` ``QuerySet`` method recursively prepopulates
1943 the cache of all one-to-many relationships ahead of time. Example::
1945 e = Entry.objects.select_related().get(id=2)
1946 print e.blog # Doesn't hit the database; uses cached version.
1947 print e.blog # Doesn't hit the database; uses cached version.
1949 ``select_related()`` is documented in the `QuerySet methods that return new QuerySets`_ section above.
1954 If a model has a ``ForeignKey``, instances of the foreign-key model will have
1955 access to a ``Manager`` that returns all instances of the first model. By
1956 default, this ``Manager`` is named ``FOO_set``, where ``FOO`` is the source
1957 model name, lowercased. This ``Manager`` returns ``QuerySets``, which can be
1958 filtered and manipulated as described in the "Retrieving objects" section
1963 b = Blog.objects.get(id=1)
1964 b.entry_set.all() # Returns all Entry objects related to Blog.
1966 # b.entry_set is a Manager that returns QuerySets.
1967 b.entry_set.filter(headline__contains='Lennon')
1970 You can override the ``FOO_set`` name by setting the ``related_name``
1971 parameter in the ``ForeignKey()`` definition. For example, if the ``Entry``
1972 model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the
1973 above example code would look like this::
1975 b = Blog.objects.get(id=1)
1976 b.entries.all() # Returns all Entry objects related to Blog.
1978 # b.entries is a Manager that returns QuerySets.
1979 b.entries.filter(headline__contains='Lennon')
1982 You cannot access a reverse ``ForeignKey`` ``Manager`` from the class; it must
1983 be accessed from an instance. Example::
1985 Blog.entry_set # Raises AttributeError: "Manager must be accessed via instance".
1987 In addition to the ``QuerySet`` methods defined in "Retrieving objects" above,
1988 the ``ForeignKey`` ``Manager`` has these additional methods:
1990 * ``add(obj1, obj2, ...)``: Adds the specified model objects to the related
1995 b = Blog.objects.get(id=1)
1996 e = Entry.objects.get(id=234)
1997 b.entry_set.add(e) # Associates Entry e with Blog b.
1999 * ``create(**kwargs)``: Creates a new object, saves it and puts it in the
2000 related object set. Returns the newly created object.
2004 b = Blog.objects.get(id=1)
2005 e = b.entry_set.create(headline='Hello', body_text='Hi', pub_date=datetime.date(2005, 1, 1))
2006 # No need to call e.save() at this point -- it's already been saved.
2008 This is equivalent to (but much simpler than)::
2010 b = Blog.objects.get(id=1)
2011 e = Entry(blog=b, headline='Hello', body_text='Hi', pub_date=datetime.date(2005, 1, 1))
2014 Note that there's no need to specify the keyword argument of the model
2015 that defines the relationship. In the above example, we don't pass the
2016 parameter ``blog`` to ``create()``. Django figures out that the new
2017 ``Entry`` object's ``blog`` field should be set to ``b``.
2019 * ``remove(obj1, obj2, ...)``: Removes the specified model objects from the
2024 b = Blog.objects.get(id=1)
2025 e = Entry.objects.get(id=234)
2026 b.entry_set.remove(e) # Disassociates Entry e from Blog b.
2028 In order to prevent database inconsistency, this method only exists on
2029 ``ForeignKey`` objects where ``null=True``. If the related field can't be
2030 set to ``None`` (``NULL``), then an object can't be removed from a
2031 relation without being added to another. In the above example, removing
2032 ``e`` from ``b.entry_set()`` is equivalent to doing ``e.blog = None``,
2033 and because the ``blog`` ``ForeignKey`` doesn't have ``null=True``, this
2036 * ``clear()``: Removes all objects from the related object set.
2040 b = Blog.objects.get(id=1)
2043 Note this doesn't delete the related objects -- it just disassociates
2046 Just like ``remove()``, ``clear()`` is only available on ``ForeignKey``s
2047 where ``null=True``.
2049 To assign the members of a related set in one fell swoop, just assign to it
2050 from any iterable object. Example::
2052 b = Blog.objects.get(id=1)
2053 b.entry_set = [e1, e2]
2055 If the ``clear()`` method is available, any pre-existing objects will be
2056 removed from the ``entry_set`` before all objects in the iterable (in this
2057 case, a list) are added to the set. If the ``clear()`` method is *not*
2058 available, all objects in the iterable will be added without removing any
2061 Each "reverse" operation described in this section has an immediate effect on
2062 the database. Every addition, creation and deletion is immediately and
2063 automatically saved to the database.
2065 One-to-one relationships
2066 ------------------------
2068 One-to-one relationships are very similar to many-to-one relationships.
2069 If you define a OneToOneField on your model, instances of that model will have
2070 access to the related object via a simple attribute of the model.
2074 class EntryDetail(models.Model):
2075 entry = models.OneToOneField(Entry)
2076 details = models.TextField()
2078 ed = EntryDetail.objects.get(id=2)
2079 ed.entry # Returns the related Entry object.
2081 The difference comes in "reverse" queries. The related model in a one-to-one
2082 relationship also has access to a ``Manager`` object, but that ``Manager``
2083 represents a single object, rather than a collection of objects::
2085 e = Entry.objects.get(id=2)
2086 e.entrydetail # returns the related EntryDetail object
2088 If no object has been assigned to this relationship, Django will raise
2089 a ``DoesNotExist`` exception.
2091 Instances can be assigned to the reverse relationship in the same way as
2092 you would assign the forward relationship::
2096 Many-to-many relationships
2097 --------------------------
2099 Both ends of a many-to-many relationship get automatic API access to the other
2100 end. The API works just as a "backward" one-to-many relationship. See Backward_
2103 The only difference is in the attribute naming: The model that defines the
2104 ``ManyToManyField`` uses the attribute name of that field itself, whereas the
2105 "reverse" model uses the lowercased model name of the original model, plus
2106 ``'_set'`` (just like reverse one-to-many relationships).
2108 An example makes this easier to understand::
2110 e = Entry.objects.get(id=3)
2111 e.authors.all() # Returns all Author objects for this Entry.
2113 e.authors.filter(name__contains='John')
2115 a = Author.objects.get(id=5)
2116 a.entry_set.all() # Returns all Entry objects for this Author.
2118 Like ``ForeignKey``, ``ManyToManyField`` can specify ``related_name``. In the
2119 above example, if the ``ManyToManyField`` in ``Entry`` had specified
2120 ``related_name='entries'``, then each ``Author`` instance would have an
2121 ``entries`` attribute instead of ``entry_set``.
2123 How are the backward relationships possible?
2124 --------------------------------------------
2126 Other object-relational mappers require you to define relationships on both
2127 sides. The Django developers believe this is a violation of the DRY (Don't
2128 Repeat Yourself) principle, so Django only requires you to define the
2129 relationship on one end.
2131 But how is this possible, given that a model class doesn't know which other
2132 model classes are related to it until those other model classes are loaded?
2134 The answer lies in the ``INSTALLED_APPS`` setting. The first time any model is
2135 loaded, Django iterates over every model in ``INSTALLED_APPS`` and creates the
2136 backward relationships in memory as needed. Essentially, one of the functions
2137 of ``INSTALLED_APPS`` is to tell Django the entire model domain.
2139 Queries over related objects
2140 ----------------------------
2142 Queries involving related objects follow the same rules as queries involving
2143 normal value fields. When specifying the the value for a query to match, you
2144 may use either an object instance itself, or the primary key value for the
2147 For example, if you have a Blog object ``b`` with ``id=5``, the following
2148 three queries would be identical::
2150 Entry.objects.filter(blog=b) # Query using object instance
2151 Entry.objects.filter(blog=b.id) # Query using id from instance
2152 Entry.objects.filter(blog=5) # Query using id directly
2157 The delete method, conveniently, is named ``delete()``. This method immediately
2158 deletes the object and has no return value. Example::
2162 You can also delete objects in bulk. Every ``QuerySet`` has a ``delete()``
2163 method, which deletes all members of that ``QuerySet``.
2165 For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
2168 Entry.objects.filter(pub_date__year=2005).delete()
2170 When Django deletes an object, it emulates the behavior of the SQL
2171 constraint ``ON DELETE CASCADE`` -- in other words, any objects which
2172 had foreign keys pointing at the object to be deleted will be deleted
2173 along with it. For example::
2175 b = Blog.objects.get(pk=1)
2176 # This will delete the Blog and all of its Entry objects.
2179 Note that ``delete()`` is the only ``QuerySet`` method that is not exposed on a
2180 ``Manager`` itself. This is a safety mechanism to prevent you from accidentally
2181 requesting ``Entry.objects.delete()``, and deleting *all* the entries. If you
2182 *do* want to delete all the objects, then you have to explicitly request a
2183 complete query set::
2185 Entry.objects.all().delete()
2187 Updating multiple objects at once
2188 =================================
2190 **New in Django development version**
2192 Sometimes you want to set a field to a particular value for all the objects in
2193 a ``QuerySet``. You can do this with the ``update()`` method. For example::
2195 # Update all the headlines with pub_date in 2007.
2196 Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
2198 You can only set non-relation fields and ``ForeignKey`` fields using this
2199 method, and the value you set the field to must be a hard-coded Python value
2200 (i.e., you can't set a field to be equal to some other field at the moment).
2202 To update ``ForeignKey`` fields, set the new value to be the new model
2203 instance you want to point to. Example::
2205 b = Blog.objects.get(pk=1)
2206 # Change every Entry so that it belongs to this Blog.
2207 Entry.objects.all().update(blog=b)
2209 The ``update()`` method is applied instantly and doesn't return anything
2210 (similar to ``delete()``). The only restriction on the ``QuerySet`` that is
2211 updated is that it can only access one database table, the model's main
2212 table. So don't try to filter based on related fields or anything like that;
2215 Extra instance methods
2216 ======================
2218 In addition to ``save()``, ``delete()``, a model object might get any or all
2219 of the following methods:
2224 For every field that has ``choices`` set, the object will have a
2225 ``get_FOO_display()`` method, where ``FOO`` is the name of the field. This
2226 method returns the "human-readable" value of the field. For example, in the
2233 class Person(models.Model):
2234 name = models.CharField(max_length=20)
2235 gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
2237 ...each ``Person`` instance will have a ``get_gender_display()`` method. Example::
2239 >>> p = Person(name='John', gender='M')
2243 >>> p.get_gender_display()
2246 get_next_by_FOO(\**kwargs) and get_previous_by_FOO(\**kwargs)
2247 -------------------------------------------------------------
2249 For every ``DateField`` and ``DateTimeField`` that does not have ``null=True``,
2250 the object will have ``get_next_by_FOO()`` and ``get_previous_by_FOO()``
2251 methods, where ``FOO`` is the name of the field. This returns the next and
2252 previous object with respect to the date field, raising the appropriate
2253 ``DoesNotExist`` exception when appropriate.
2255 Both methods accept optional keyword arguments, which should be in the format
2256 described in `Field lookups`_ above.
2258 Note that in the case of identical date values, these methods will use the ID
2259 as a fallback check. This guarantees that no records are skipped or duplicated.
2260 For a full example, see the `lookup API sample model`_.
2262 .. _lookup API sample model: ../models/lookup/
2267 For every ``FileField``, the object will have a ``get_FOO_filename()`` method,
2268 where ``FOO`` is the name of the field. This returns the full filesystem path
2269 to the file, according to your ``MEDIA_ROOT`` setting.
2271 Note that ``ImageField`` is technically a subclass of ``FileField``, so every
2272 model with an ``ImageField`` will also get this method.
2277 For every ``FileField``, the object will have a ``get_FOO_url()`` method,
2278 where ``FOO`` is the name of the field. This returns the full URL to the file,
2279 according to your ``MEDIA_URL`` setting. If the value is blank, this method
2280 returns an empty string.
2285 For every ``FileField``, the object will have a ``get_FOO_size()`` method,
2286 where ``FOO`` is the name of the field. This returns the size of the file, in
2287 bytes. (Behind the scenes, it uses ``os.path.getsize``.)
2289 save_FOO_file(filename, raw_contents)
2290 -------------------------------------
2292 For every ``FileField``, the object will have a ``save_FOO_file()`` method,
2293 where ``FOO`` is the name of the field. This saves the given file to the
2294 filesystem, using the given filename. If a file with the given filename already
2295 exists, Django adds an underscore to the end of the filename (but before the
2296 extension) until the filename is available.
2298 get_FOO_height() and get_FOO_width()
2299 ------------------------------------
2301 For every ``ImageField``, the object will have ``get_FOO_height()`` and
2302 ``get_FOO_width()`` methods, where ``FOO`` is the name of the field. This
2303 returns the height (or width) of the image, as an integer, in pixels.
2308 As you develop views, you will discover a number of common idioms in the
2309 way you use the database API. Django encodes some of these idioms as
2310 shortcuts that can be used to simplify the process of writing views. These
2311 functions are in the ``django.shortcuts`` module.
2316 One common idiom to use ``get()`` and raise ``Http404`` if the
2317 object doesn't exist. This idiom is captured by ``get_object_or_404()``.
2318 This function takes a Django model as its first argument and an
2319 arbitrary number of keyword arguments, which it passes to the default
2320 manager's ``get()`` function. It raises ``Http404`` if the object doesn't
2321 exist. For example::
2323 # Get the Entry with a primary key of 3
2324 e = get_object_or_404(Entry, pk=3)
2326 When you provide a model to this shortcut function, the default manager
2327 is used to execute the underlying ``get()`` query. If you don't want to
2328 use the default manager, or if you want to search a list of related objects,
2329 you can provide ``get_object_or_404()`` with a ``Manager`` object instead.
2332 # Get the author of blog instance e with a name of 'Fred'
2333 a = get_object_or_404(e.authors, name='Fred')
2335 # Use a custom manager 'recent_entries' in the search for an
2336 # entry with a primary key of 3
2337 e = get_object_or_404(Entry.recent_entries, pk=3)
2339 **New in Django development version:** The first argument to
2340 ``get_object_or_404()`` can be a ``QuerySet`` object. This is useful in cases
2341 where you've defined a custom manager method. For example::
2343 # Use a QuerySet returned from a 'published' method of a custom manager
2344 # in the search for an entry with primary key of 5
2345 e = get_object_or_404(Entry.objects.published(), pk=5)
2350 ``get_list_or_404`` behaves the same way as ``get_object_or_404()``
2351 -- except that it uses ``filter()`` instead of ``get()``. It raises
2352 ``Http404`` if the list is empty.
2354 Falling back to raw SQL
2355 =======================
2357 If you find yourself needing to write an SQL query that is too complex for
2358 Django's database-mapper to handle, you can fall back into raw-SQL statement
2361 The preferred way to do this is by giving your model custom methods or custom
2362 manager methods that execute queries. Although there's nothing in Django that
2363 *requires* database queries to live in the model layer, this approach keeps all
2364 your data-access logic in one place, which is smart from an code-organization
2365 standpoint. For instructions, see `Executing custom SQL`_.
2367 Finally, it's important to note that the Django database layer is merely an
2368 interface to your database. You can access your database via other tools,
2369 programming languages or database frameworks; there's nothing Django-specific
2370 about your database.
2372 .. _Executing custom SQL: ../model-api/#executing-custom-sql