0

私は 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しかし、 2 回定義することで繰り返していることがわかります。category上部で一度定義したクラスに新しいプロパティを追加して、 and で参照self.categoryする方法はget_queryset()ありget_context_data()ますか?

4

3 に答える 3

3

別の角度からアプローチする必要があると思います。 の をListView表示するLocationsのではCategoryなく、DetailViewそのカテゴリの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

これで、テンプレートで使用できるコンテキスト内のカテゴリと場所のリストの両方ができました。

于 2012-03-15T20:34:20.203 に答える
2

にカテゴリを割り当てるだけselfです。唯一の注意点は、一部のメソッドが他のメソッドより先に呼び出されるため、どこでそれを行うかについて少し注意する必要があるということです。ただし、get_querysetビューで最初にアクティブ化されるものの 1 つであるため、そこでは正常に機能します。

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 ドキュメントで使用されている正確な方法です (3 番目のコード サンプルを下に示します)。

于 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 に答える