2012-03-15 3 views
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이라는 클래스에 새 속성을 추가 할 수있는 방법이 있습니까? 을 get_queryset()get_context_data()에 입력하면됩니다. 난 당신이 다른 각도에서 접근해야한다고 생각이 self.category()

답변

3

에 액세스 할 것이다 장식없이,

+0

+1. 또한,'get_context_data' 메소드를 완전히 삭제하고,'{% with location_list = category.location_set.all %}'를 템플릿에 추가함으로써 코드를 단순화 할 수 있습니다. –

+0

이것은 내가하려고했던 것보다 훨씬 의미가 있습니다. 감사! – user1272534

1

는 클래스 내부의 @property 장식

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

를 사용하고 당신은 self.category로 액세스 할 수 있습니다 : CategoryLocations을 표시하는 ListView을 사용하지 말고 을 포함하는 CategoryDetailView을 사용해야합니다. 뷰 클래스의 이름은 또한 카테고리의 상세 뷰를 표시하고 있음을 나타냅니다. 나는 다음과 같이 보일 것입니다 :

템플릿에 사용할 수있는 범주와 위치 목록이 컨텍스트에 모두 있습니다.

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 (세 번째 코드 샘플 아래)에서 사용하는 정확한 방법이다.

관련 문제