| 1 | """ |
| 2 | 36. get_object_or_404() |
| 3 | |
| 4 | get_object_or_404 is a shortcut function to be used in view functions for |
| 5 | performing a get() lookup and raising a Http404 exception if a DoesNotExist |
| 6 | exception was rasied during the get() call. |
| 7 | """ |
| 8 | |
| 9 | from django.db import models |
| 10 | from django.http import Http404 |
| 11 | from django.shortcuts import get_object_or_404 |
| 12 | |
| 13 | class Author(models.Model): |
| 14 | name = models.CharField(maxlength=50) |
| 15 | |
| 16 | def __str__(self): |
| 17 | return self.name |
| 18 | |
| 19 | class Article(models.Model): |
| 20 | author = models.ForeignKey(Author) |
| 21 | title = models.CharField(maxlength=50) |
| 22 | |
| 23 | def __str__(self): |
| 24 | return "%s by %s" % (self.title, self.author) |
| 25 | |
| 26 | __test__ = {'API_TESTS':""" |
| 27 | # Let's create an Author. |
| 28 | >>> a = Author.objects.create(name="Brave Sir Robin") |
| 29 | |
| 30 | # No Articles yet so we should get a Http404 error. |
| 31 | >>> get_object_or_404(Article, title="Foo") == Http404 |
| 32 | Traceback (most recent call last): |
| 33 | ... |
| 34 | Http404 |
| 35 | |
| 36 | # Let's create an Article. |
| 37 | >>> article = Article.objects.create(author=a, title="Run away!") |
| 38 | |
| 39 | # get_object_or_404 can be passed a Model to query. |
| 40 | >>> get_object_or_404(Article, title__contains="Run") |
| 41 | <Article: Run away! by Brave Sir Robin> |
| 42 | |
| 43 | # We can also use the the Article manager through an Author object. |
| 44 | >>> get_object_or_404(a.article_set, title__contains="Run") |
| 45 | <Article: Run away! by Brave Sir Robin> |
| 46 | |
| 47 | # This should raise a Http404 error. |
| 48 | >>> get_object_or_404(a.article_set, title__contains="Camelot") |
| 49 | Traceback (most recent call last): |
| 50 | ... |
| 51 | Http404 |
| 52 | """} |