我是整个Django的新手,因此,我决定从ClassBased GenericViews开始,而不是从较早的基于Generics的函数开始,这导致缺乏文档的情况有些麻烦。无论如何,到目前为止,我真的很喜欢GenericViews并一直在使用装饰器进行扩展。
我一直在做的简单例子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
我的问题是,就总体可读性和可维护性而言,是否存在“更好”或“更可接受”的方式?还是仅仅是编码风格偏好?
我问的原因是,尽管我认为这种方式更具可读性,但我希望有一天能以此赚钱,并且不想养成奇怪的编码习惯,这会激怒同事,因此几乎没有任何投入编码风格非常受赞赏。谢谢。
最佳答案
这是执行此操作的正确方法(我已经编辑了您的代码):ideapad/views.py
from django.views.generic import ListView
from ideapad.models import Idea
from sauce.decorators import SortQuerysetMixin
class IndexListView(SortQuerysetMixin, ListView):
default_sort = '-date'
model = Idea
template_name = 'ideapad/index.html'
context_object_name = 'ideas'
sauce/decorators.py
class SortQuerysetMixin(object):
def get_queryset(self):
queryset = super(SortQuerysetMixin, self).get_queryset()
sortmethod = self.request.GET.get('sort', self.default_sort)
if hasattr(queryset, 'order_by'):
queryset = queryset.order_by(sortmethod)
return queryset