| 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 ArticleManager(models.Manager): |
| 20 | def get_query_set(self): |
| 21 | return super(ArticleManager, self).get_query_set().filter(author__name__icontains='sir') |
| 22 | |
| 23 | class Article(models.Model): |
| 24 | author = models.ForeignKey(Author) |
| 25 | title = models.CharField(maxlength=50) |
| 26 | objects = models.Manager() |
| 27 | by_a_sir = ArticleManager() |
| 28 | |
| 29 | def __str__(self): |
| 30 | return "%s by %s" % (self.title, self.author) |
| 31 | |
| 32 | __test__ = {'API_TESTS':""" |
| 33 | # Let's create an Author. |
| 34 | >>> a = Author.objects.create(name="Brave Sir Robin") |
| 35 | |
| 36 | # No Articles yet so we should get a Http404 error. |
| 37 | >>> get_object_or_404(Article, title="Foo") == Http404 |
| 38 | Traceback (most recent call last): |
| 39 | ... |
| 40 | Http404 |
| 41 | |
| 42 | # Let's create an Article. |
| 43 | >>> article = Article.objects.create(author=a, title="Run away!") |
| 44 | |
| 45 | # get_object_or_404 can be passed a Model to query. |
| 46 | >>> get_object_or_404(Article, title__contains="Run") |
| 47 | <Article: Run away! by Brave Sir Robin> |
| 48 | |
| 49 | # We can also use the the Article manager through an Author object. |
| 50 | >>> get_object_or_404(a.article_set, title__contains="Run") |
| 51 | <Article: Run away! by Brave Sir Robin> |
| 52 | |
| 53 | # No articles containing "Camelot". This should raise a Http404 error. |
| 54 | >>> get_object_or_404(a.article_set, title__contains="Camelot") |
| 55 | Traceback (most recent call last): |
| 56 | ... |
| 57 | Http404 |
| 58 | |
| 59 | # Custom managers can be used too. |
| 60 | >>> get_object_or_404(Article.by_a_sir, title="Run away!") |
| 61 | <Article: Run away! by Brave Sir Robin> |
| 62 | """} |