| 259 | |
| 260 | .. _retrieving-single-object-with-get: |
| 261 | |
| 262 | Retrieving a single object with get |
| 263 | ----------------------------------- |
| 264 | |
| 265 | ``.filter()`` will always give you a ``QuerySet``, even if only a single |
| 266 | object matches the query - in this case, it will be a ``QuerySet`` containing |
| 267 | a single element. |
| 268 | |
| 269 | If you know there is only one object that matches your query, you can use |
| 270 | the ``get()`` method on a `Manager` which returns the object directly:: |
| 271 | |
| 272 | >>> one_entry = Entry.objects.get(pk=1) |
| 273 | |
| 274 | You can use any query expression with ``get()``, just like with ``filter()`` - |
| 275 | again, see `Field lookups`_ below. |
| 276 | |
| 277 | Note 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 |
| 279 | query, ``.get()`` will raise a ``DoesNotExist`` exception. This exception is an |
| 280 | attribute of the model class that the query is being performed on - so in the |
| 281 | code above, if there is no ``Entry`` object with a primary key of 1, Django will |
| 282 | raise ``Entry.DoesNotExist``. |
| 283 | |
| 284 | Similarly, Django will complain if more than one item matches the ``get()`` |
| 285 | query. In this case, it will raise ``MultipleObjectsReturned``, which again is |
| 286 | an attribute of the model class itself. |
| 287 | |
| 288 | |
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. |
| 292 | Most of the time you'll use ``all()``, ``get()``, ``filter()`` and ``exclude()`` |
| 293 | when you need to look up objects from the database. However, that's far from all |
| 294 | there is; see the :ref:`QuerySet API Reference <queryset-api>` for a complete |
| 295 | list of all the various ``QuerySet`` methods. |