我是Python的新手,並試圖找出Django 1.3的基於類的通用視圖。現在,我有以下視圖,它獲取類別中的位置對象列表:Django通用視圖:如何分配一個新的屬性?
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
的課程中,我在頂部定義了一次,然後僅在get_queryset()
和get_context_data()
中引用self.category
?
+1。此外,您可以通過完全刪除'get_context_data'方法來進一步簡化代碼,並將{%with location_list = category.location_set.all%}'放在模板中。 – 2012-03-15 20:38:59
這比我想要做的更有意義。謝謝! – user1272534 2012-03-15 21:46:25