Good day! Tell me pliz. There are sections of the catalog, 3 levels of nesting, goods are attached to sections, it is necessary for each section to output the number of goods located in it, taking into account the subsidiary subsections. The number of products varies depending on the filter, for example, if a specific brand or price range is indicated.
I read about the aggregation but did not understand how to apply it to MPTT
How can this be done by means of Django orm, and in the future there will be about a million products in the database, how to do it optimally with a reserve of such quantity.
The base is used by Postgresql-9.5, it all works on Centos 7, Python 3, Django 1.10.2
Below are the models of sections and products, as well as the code from the template
class Category(MPTTModel): name = models.CharField('Π Π°Π·Π΄Π΅Π»', max_length=100) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class MPTTMeta: order_insertion_by = ['sort'] class Meta: verbose_name = 'Π Π°Π·Π΄Π΅Π»' verbose_name_plural = 'Π Π°Π·Π΄Π΅Π»Ρ' def __str__(self): return '%s%s' % ('- ' * self.level, self.name) class Product(models.Model): parent = models.ForeignKey(Category) name = models.CharField('ΠΠ°Π·Π²Π°Π½ΠΈΠ΅', max_length=100) price = models.IntegerField('Π¦Π΅Π½Π°') size = models.ManyToManyField(Size) color = models.ManyToManyField(Color) vendor = models.ForeignKey(Brand, blank=True) shop = models.ForeignKey(Company, blank=True) class Meta: verbose_name = 'Π’ΠΎΠ²Π°Ρ' verbose_name_plural = 'Π’ΠΎΠ²Π°ΡΡ' def __str__(self): return self.name def product_list(request, category_slug=False): category = None object_list = Product.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) object_list = object_list.filter(parent__in=category.get_descendants(include_self=True)) paginator = Paginator(object_list, 3) page = request.GET.get('page') sections = Category.objects.all() try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) return render( request, 'catalog/product_list.html', { 'page': page, 'category': category, 'sections': sections, 'products': products } ) {% load mptt_tags %} <ul> {% recursetree sections %} <li{% if node == category %} class="active"{% endif %}> <a href="/catalog/{{ node.slug }}/">{{ node.name }}</a> {% if not node.is_leaf_node %} <ul> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> I want to get something like
<a href="/catalog/{{ node.slug }}/">{{ node.name }} ({{ node.cnt }})</a>