2012-03-15 21 views
0

我是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

回答

3

我想你應該從不同的角度接近它:您不應該使用ListView顯示CategoryLocations,而是CategoryDetailView,其中還包括該類別的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 

你現在有兩個類別,並在你的背景下的位置,你可以在模板中使用列表。

+0

+1。此外,您可以通過完全刪除'get_context_data'方法來進一步簡化代碼,並將{%with location_list = category.location_set.all%}'放在模板中。 – 2012-03-15 20:38:59

+0

這比我想要做的更有意義。謝謝! – user1272534 2012-03-15 21:46:25

1

使用@property裝飾

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

你的類中,然後您可以訪問它爲self.category,沒有裝飾這將是訪問與self.category()

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,這其實是由​​(第三代碼示例下)所使用的精確方法。

相關問題