Доброго времени суток!
Может кто знает. Как выводить count в категириях и суб-категориях, используя django-mptt?
Примерно так:
Cars & Vehicles (63)
Heavy Vehicles (15)
Machinery & Construction (13)
Motorcycles & Bikes (10)
Commercial Vehicles (15)
Vehicle Accessories (10)
Мой views.py
def show_category(request, hierarchy):
# print('>> ' + hierarchy)
category_slug = hierarchy.split('/')
parent = None
union = None
testing = None
root = Category.objects.all()
context = {'nodes': root}
# condext['count'] = Category.objects.filter(slug = hierarchy).count()
context['category_slug'] = category_slug
context['root'] = root
# condext['roots'] = Category.get_descendant_count()
urllink = category_slug[-1]
union = Union.objects.all()
context['union'] = hierarchy
testing = Union.objects.filter(category__slug = hierarchy)
context['count'] = Union.objects.filter(slug = category_slug).count()
# condext['count'] = root.filter(slug = hierarchy).count()
context['testing'] = testing
return render(request, "categories/cat.html", context)
cat.html
<ul>
{% recursetree nodes %}
<li>
<a href="/categories/{{ node.slug }}/">{{ node.name }}</a> ({{ node.get_bug_count }})
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
models.py
class Category(MPTTModel):
name = models.CharField(max_length=128, null=True, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
slug = models.CharField(max_length=128, null=True, blank=True, default='')
def get_products(self):
return self.product_set.all()
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
return '%s / %s' % (self.name, self.parent)
def save(self, *args, **kwargs):
if not self.id:
if self.parent:
self.slug = self.parent.slug + '/' + slugify(self.name)
# print('if ' + self.slug)
else:
self.slug = slugify(self.name)
# print("else " + self.slug)
super(Category, self).save(*args, **kwargs)
def get_bug_count(self):
return Union.objects.filter(category=self).count()
Updated 2 June 2018, 17:41 by HunterNomad.