Hi Linan,

On Sep 22, 3:38 am, Linan <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I just wrote a decorator to validate if an object(say Blog) exists:
>
> def require_blog_item_exists(func):
>     def _decorated_func(request, blog_id, *args, **kwargs):
>         try:
>             blog = Blog.objects.get(id = blog_id)
>             return func(request, blog_id, *args, **kwargs)
>         except:
>             return HttpResponseRedirect('error')
>     return _decorated_func
>
> An idea pops into my mind, that why not cache the blog object in
> func.func_globals to avoid extra database retrieval operation? So I
> wrote following codes:

I think a better way to save yourself the repeated database retrieval
would be to use your decorator to modify the arguments to you view
function.

So where you return the original function above, do this instead:
               return func(request, blog, *args, **kwargs)

And then modify all your view functions that use this decorator so
that they take the actual blog as an argument rather than just the id
returned by the URL conf. I'm not sure if this moves beyond what a
decorator is meant to do, but it seems to be similar to the permalink
decorator (in django.db.models.__init__.py) that requires changing the
return value of your get_absolute_url method before using it.

Hope that helps,
Michael.

Cheers,
Michael


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to