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