0

カテゴリ/models.py

from django.db import models

from treebeard.mp_tree import MP_Node


class Category(MP_Node):
    title = models.CharField(max_length=50)
    slug = models.SlugField(unique=True)

    node_order_by = ['title']

    class Meta:
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return 'Category: {}'.format(self.title)

カテゴリ/views.py

from django.views.generic import DetailView

from .models import Category


class CategoryDetailView(DetailView):
    model = Category
    context_object_name = 'category'
    template_name = 'categories/category_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["products_in_category"] = self.object.products.filter(active=True)
        return context

category_detail.html

.....
{% for p in products_in_category %}
       
        <h2><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h2>

.....

上記のコードは、特定のカテゴリに属する​​製品を表示するのに適していますが、その子孫に属する製品を表示することもできます。

例:

shoes

├── sneakers
│   ├── laced sneakers
│   └── non-laced sneakers

スニーカーのカテゴリーページにある場合、レース付きスニーカーとレースなしスニーカーの両方に関連する商品を表示できるようにしたいと考えています。

私の考えでは、 get_context_data は次のようになります

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["products_in_category"] = self.object.get_descendants().products.filter(active=True)
    return context

しかし残念ながら、それはうまくいきませんでした。

代わりにListViewを使用することを考えていましたが、カテゴリページにはカテゴリを説明する説明があり、そのため、DetailViewの方が適していると思います.

皆さんは、どのようなアプローチが最善だと思いますか?

4

1 に答える 1