Ticket #14120: making_queries.diff

File making_queries.diff, 2.4 KB (added by Daniel Roseman, 14 years ago)

documentation patch

  • docs/topics/db/queries.txt

     
    160160that cannot be evaluated. The ``all()`` method returns a ``QuerySet`` that
    161161*can* be evaluated.)
    162162
     163
    163164Retrieving specific objects with filters
    164165----------------------------------------
    165166
     
    255256``QuerySet`` is *evaluated* by accessing the database. For more details on
    256257exactly when evaluation takes place, see :ref:`when-querysets-are-evaluated`.
    257258
     259
     260.. _retrieving-single-object-with-get:
     261
     262Retrieving a single object with get
     263-----------------------------------
     264
     265``.filter()`` will always give you a ``QuerySet``, even if only a single
     266object matches the query - in this case, it will be a ``QuerySet`` containing
     267a single element.
     268
     269If you know there is only one object that matches your query, you can use
     270the ``get()`` method on a `Manager` which returns the object directly::
     271
     272    >>> one_entry = Entry.objects.get(pk=1)
     273
     274You can use any query expression with ``get()``, just like with ``filter()`` -
     275again, see `Field lookups`_ below.
     276
     277Note that there is a difference between using ``.get()``, and using
     278``.filter()`` with a slice of ``[0]``. If there are no results that match the
     279query, ``.get()`` will raise a ``DoesNotExist`` exception. This exception is an
     280attribute of the model class that the query is being performed on - so in the
     281code above, if there is no ``Entry`` object with a primary key of 1, Django will
     282raise ``Entry.DoesNotExist``.
     283
     284Similarly, Django will complain if more than one item matches the ``get()``
     285query. In this case, it will raise ``MultipleObjectsReturned``, which again is
     286an attribute of the model class itself.
     287
     288
    258289Other QuerySet methods
    259 ~~~~~~~~~~~~~~~~~~~~~~
     290----------------------
    260291
    261 Most of the time you'll use ``all()``, ``filter()`` and ``exclude()`` when you
    262 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
    263 of all the various ``QuerySet`` methods.
     292Most of the time you'll use ``all()``, ``get()``, ``filter()`` and ``exclude()``
     293when you need to look up objects from the database. However, that's far from all
     294there is; see the :ref:`QuerySet API Reference <queryset-api>` for a complete
     295list of all the various ``QuerySet`` methods.
    264296
    265297.. _limiting-querysets:
    266298
Back to Top