Django mptt:获取类别的所有后代
Django mptt: Get all descendants of a category
我希望我的类别显示该类别中的所有项目,包括子类别,因此父类别包含子类别的所有项目。
我已尝试将此方法添加到我在 models.py
中的类别 class
def get_all_products(self):
# To display all items from all subcategories
return Product.objects.filter(category__in=Category.objects.get_descendants(include_self=True))
并将此添加到我的 template.html,但它不起作用。我做错了什么?
{% for product in instance.get_all_products %}
<li>{{ product.product_name }}</li>
{% empty %}
<li>No items</li>
{% endfor %}
我已经意识到哪里出错了,正确的代码是:
def get_all_products(self):
# To display all items from all subcategories
return Product.objects.filter(category__in=self.get_descendants(include_self=True))
{% for product in product.get_all_products %}
<li>{{ product.product_name }}</li>
{% empty %}
<li>No items</li>
{% endfor %}
在我使用的视图函数中:
products = models.Product.objects.filter(category__in=category.get_descendants(include_self=True))
我希望我的类别显示该类别中的所有项目,包括子类别,因此父类别包含子类别的所有项目。
我已尝试将此方法添加到我在 models.py
中的类别 classdef get_all_products(self):
# To display all items from all subcategories
return Product.objects.filter(category__in=Category.objects.get_descendants(include_self=True))
并将此添加到我的 template.html,但它不起作用。我做错了什么?
{% for product in instance.get_all_products %}
<li>{{ product.product_name }}</li>
{% empty %}
<li>No items</li>
{% endfor %}
我已经意识到哪里出错了,正确的代码是:
def get_all_products(self):
# To display all items from all subcategories
return Product.objects.filter(category__in=self.get_descendants(include_self=True))
{% for product in product.get_all_products %}
<li>{{ product.product_name }}</li>
{% empty %}
<li>No items</li>
{% endfor %}
在我使用的视图函数中:
products = models.Product.objects.filter(category__in=category.get_descendants(include_self=True))