I’m new at this whole Django thing and as such, I’ve decided to start off with the ClassBased GenericViews rather than the older function based Generics, which has caused a couple stumbling blocks do to lack of documentation. Anyway, so far I really like the GenericViews and have been extending them with decorators.
Simple example of what I’ve been doing
ideapad/urls.py
from ideapad.views import *
urlpatterns = patterns('ideapad.views',
url(r'^$', IndexListView.as_view(), name='url_index'),
)
ideapad/views.py
from django.views.generic import ListView
from ideapad.models import Idea
from sauce.decorators import sort_queryset
@sort_queryset('-date')
class IndexListView(ListView):
model = Idea
template_name = 'ideapad/index.html'
context_object_name = 'ideas'
sauce/decorators.py
def sort_queryset(default_sort):
"""
Decorator that sorts queryset according to GET data
Made to wrap GenericViews with get_queryset methods
"""
def decorator(cls):
fn=cls.get_queryset
def wrapper(self):
queryset = fn(self)
sortmethod = self.request.GET.get('sort', default_sort)
if hasattr(queryset, 'order_by'):
queryset = queryset.order_by(sortmethod)
return queryset
cls.get_queryset=wrapper
return cls
return decorator
My question is, as a matter of overall readability and maintainability, is there a ‘better’ or ‘more acceptable’ way of doing this? Or is it just a coding style preference?
Reason I ask is, while I think it’s more readable this way, I’d like to make money doing this some day and don’t want to develop strange coding habits that are going to piss off co-workers so pretty much any input on coding style is much appreciated. Thanks.
This is proper way to do this (I have edited your code):
ideapad/views.pysauce/decorators.py