0

我是 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.categoryget_queryset()get_context_data()

4

3 回答 3

3

我认为您应该从不同的角度来处理它:您不应该使用ListView显示Locationsa 的 aCategory而是显示 aDetailView的 aCategory也包括该Locations类别的 a。您的视图类的名称还表明您正在显示一个类别的详细视图。我认为它应该看起来更像这样:

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

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

于 2012-03-15T20:34:20.203 回答
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 文档在基于类的视图上使用的确切方法(第三个代码示例向下)。

于 2012-03-15T20:35:07.490 回答
1

使用@property装饰器

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

在你的班级里面,然后你可以访问它self.category,没有装饰器,它可以通过self.category()

于 2012-03-15T20:19:08.143 回答