Proposal: get_or_404()

144 views
Skip to first unread message

Adrian Holovaty

unread,
Sep 22, 2005, 6:44:12 PM9/22/05
to django-d...@googlegroups.com
Here's a common pattern in views:

def foo_detail(request, some_lookup):
try:
f = foos.get_object(some_field__exact=some_lookup)
except foos.FooDoesNotExist:
raise Http404

I propose a new helper function in django.core.extensions,
get_or_404(), which would do this:

def foo_detail(request, some_lookup):
f = get_or_404(foos, some_field__exact=some_lookup)

The function would raise Http404 if the object doesn't exist.

This is a prime candidate for inclusion in django/core/extensions.py,
which is where we put functions that "span" several layers of MVC.

Thoughts?

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com | chicagocrime.org

Paul Bowsher

unread,
Sep 22, 2005, 6:50:11 PM9/22/05
to django-d...@googlegroups.com
+1 here
--
Paul Bowsher
IT Systems Developer
Simply Stuck Ltd

Robert Wittams

unread,
Sep 22, 2005, 8:14:51 PM9/22/05
to django-d...@googlegroups.com
Sounds good to me.

Simon Willison

unread,
Sep 23, 2005, 2:59:39 AM9/23/05
to django-d...@googlegroups.com

On 22 Sep 2005, at 15:44, Adrian Holovaty wrote:

> def foo_detail(request, some_lookup):
> try:
> f = foos.get_object(some_field__exact=some_lookup)
> except foos.FooDoesNotExist:
> raise Http404

This is another prime candidate for a decorator:

@on_not_exist_404
def foo_detail(request, some_lookup):
f = foos.get_object(some_field__exact=some_lookup)
...

Cheers,

Simon

Adrian Holovaty

unread,
Sep 23, 2005, 5:40:56 PM9/23/05
to django-d...@googlegroups.com
On 9/22/05, Adrian Holovaty <holo...@gmail.com> wrote:
> I propose a new helper function in django.core.extensions,
> get_or_404(), which would do this:
>
> def foo_detail(request, some_lookup):
> f = get_or_404(foos, some_field__exact=some_lookup)

I've added get_object_or_404 and get_list_or_404 to django/core/extensions.py.
Reply all
Reply to author
Forward
0 new messages