我是 Python 新手,试图弄清楚 Django 1.3 的基于类的通用视图。现在,我有以下视图,它获取类别中的位置对象列表:
class category_detail(ListView):
"""Return a generic view of locations in a category."""
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context.
context = super(category_detail, self).get_context_data(**kwargs)
# Add the current category to the context.
category = get_object_or_404(Category, slug=self.kwargs['slug'])
context['category'] = category
return context
def get_queryset(self):
category = get_object_or_404(Category, slug=self.kwargs['slug'])
return Location.objects.filter(category=category)
它做我想让它做的事情。但是你可以看到我通过定义category
两次来重复自己。有没有办法可以将一个新属性添加到我在顶部定义一次的类中category
,然后只引用and ?self.category
get_queryset()
get_context_data()