Django Generic Views:如何分配新属性?

时间:2012-03-15 20:12:58

标签: python django class django-generic-views

我是Python的新手,并试图找出Django 1.3的基于类的通用视图。现在,我有以下视图,它获取类别中的Location对象列表:

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的类中,我在顶部定义一次,然后只引用self.categoryget_queryset()中的get_context_data()?< / p>

3 个答案:

答案 0 :(得分:3)

我认为你应该从不同的角度来看待它:你不应该使用ListView来显示Locations CategoryDetailView Category Locations还包括该类别的class CategoryLocationsView(DetailView): model = Category context_object_name = 'category' def get_context_data(self, **kwargs): context = super(CategoryLocationsView, self).get_context_data(**kwargs) context['location_list'] = self.get_object().location_set.all() return context 。视图类的名称还表明您正在显示类别的详细视图。我认为看起来应该更像这样:

{{1}}

您现在拥有上下文中的类别和位置列表,您可以在模板中使用这些位置。

答案 1 :(得分:2)

只需将类别分配给self即可。唯一需要注意的是,你需要对自己的位置做一点小心,因为有些方法会先于其他方法调用。但是,get_queryset是视图上激活的第一件事之一,所以它在那里工作正常:

def get_queryset(self):
    self.category = get_object_or_404(Category, slug=self.kwargs['slug'])
    return Location.objects.filter(category=self.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.
    context['category'] = self.category
    return context

FWIW,这实际上是Django docs on class-based views使用的确切方法(第三个代码示例向下)。

答案 2 :(得分:1)

使用@property装饰器

@property
def category(self):
    return get_object_or_404(Category, slug=self.kwargs['slug'])

在您的课程内,然后您可以self.category访问它,没有装饰器,self.category()

可以访问它