diff options
| author | Baptiste Mispelon <bmispelon@gmail.com> | 2013-11-19 15:25:15 +0100 |
|---|---|---|
| committer | Baptiste Mispelon <bmispelon@gmail.com> | 2013-11-19 19:56:06 +0100 |
| commit | 20e322f4bfaf903e0dc45d157b7a7c95d6ab4391 (patch) | |
| tree | aeb7514cc9012e6b9a52a9521f1ee17d27a9e0a1 /docs | |
| parent | ac2ef4af7cb7b462b2b1801d6cdcc4774de9ed8b (diff) | |
[1.6.x] Added more examples to the get_object_or_404 documentation.
Backport of ebfa508fa32b27de6f3e2ca04c81b46408b0506e from master.
Diffstat (limited to 'docs')
| -rw-r--r-- | docs/topics/http/shortcuts.txt | 33 |
1 files changed, 30 insertions, 3 deletions
diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt index dbdc966d9d..bd2c0d7c0f 100644 --- a/docs/topics/http/shortcuts.txt +++ b/docs/topics/http/shortcuts.txt @@ -239,9 +239,10 @@ Required arguments ------------------ ``klass`` - A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or - :class:`~django.db.models.query.QuerySet` instance from which to get the - object. + A :class:`~django.db.models.Model` class, + a :class:`~django.db.models.Manager`, + or a :class:`~django.db.models.query.QuerySet` instance from which to get + the object. ``**kwargs`` Lookup parameters, which should be in the format accepted by ``get()`` and @@ -268,6 +269,32 @@ This example is equivalent to:: except MyModel.DoesNotExist: raise Http404 +The most common use case is to pass a :class:`~django.db.models.Model`, as +shown above. However, you can also pass a +:class:`~django.db.models.query.QuerySet` instance:: + + queryset = Book.objects.filter(title__startswith='M') + get_object_or_404(queryset, pk=1) + +The above example is a bit contrived since it's equivalent to doing:: + + get_object_or_404(Book, title__startswith='M', pk=1) + +but it can be useful if you are passed the ``queryset`` variable from somewhere +else. + +Finally, you can also use a :class:`~django.db.models.Manager`. This is useful +for example if you have a +:ref:`custom manager<custom-managers>`:: + + get_object_or_404(Book.dahl_objects, title='Matilda') + +You can also use +:class:`related managers<django.db.models.fields.related.RelatedManager>`:: + + author = Author.objects.get(name='Roald Dahl') + get_object_or_404(author.book_set, title='Matilda') + Note: As with ``get()``, a :class:`~django.core.exceptions.MultipleObjectsReturned` exception will be raised if more than one object is found. |
