1

I have a category tree, with Items entry related to the category. So this is my model file:

from django.db import models
import mptt

class Category(models.Model):
 nombre=models.CharField(max_length=70)
 padre=models.ForeignKey('self', blank=True, null=True)

 def __unicode__(self):
  return self.nombre

 class Meta:
  ordering = ['tree_id', 'lft']

# Create your models here.

class Item(models.Model):
    category=models.ManyToManyField(Category)

try:
 mptt.register(Category, order_insertion_by=['nombre'], parent_attr='padre')
except mptt.AlreadyRegistered:
 pass

I'm using ManyToManyField because each item can be in more than one category.

Now, after installing 'mptt' in my apps. I'm trying the following in the shell:

Category.tree.add_related_count(Category.tree.root_nodes(), Item,
    'category', 'q_c', cumulative=True)

Which should return a tree, and load the number of Items belonging to a node on each node. This seems like standard functionality of django-mptt as stated in the documentation.

However, I get an error. The following is the trace:

http://pastebin.com/m69ed1937

Using SVN django-mptt and django 1.1 in Ubuntu 9.1.

Ezequiel
  • 668
  • 2
  • 9
  • 25
  • 1
    your example follows the docs, but in the docs, they have category being a foreignkey instead of a manytomany. – Brandon Henry Feb 05 '10 at 00:48
  • Yes, I've noticed that... I posted this as an issue to see if I have any answers from the creator. I just tried with ForeignKey and it works (since the tables are empty, it returns []). Maybe what I'm requiring is not implemented yet? – Ezequiel Feb 05 '10 at 16:59

2 Answers2

1

I ended up implementing a very similar query for a site I'm working on manually. Here's the code:

tree = Table1.objects.extra(select={"tree_content_count":
 """SELECT COUNT(DISTINCT %(join_table_fk1_name)s)
      FROM %(join_table)s
      WHERE %(join_table_fk2_name)s in
      (
        SELECT id FROM %(data_table)s m2 where m2.tree_id = %(data_table)s.tree_id
          and m2.lft between %(data_table)s.lft and %(data_table)s.rght
      )""" % {params_dict_here}
 })

This seems to do the trick. This is a full-hierarchy count; in other words, putting five things in "child1", eight things in "child2" and one in "parent" will give the following counts:

parent (14)
+-- child1 (5)
+-- child2 (8)

If you want a count which only includes things at a particular level (and not things that are underneath it in the hierarchy) you'll have to modify the in-most select statement.

willm1
  • 116
  • 2
  • Can you share how you implemented this? Can you show an example of your model, view and template. I'm trying to do the same thing, see my question here > http://stackoverflow.com/questions/14160416/django-count-items-and-ordered-by-parent-category-and-child-categories – Garth Humphreys Jan 07 '13 at 13:57
0

Try using:

Category.tree.add_related_count(Category.objects.all(), Item, 'category', 'q_c', cumulative=True)
panjianom
  • 236
  • 4
  • 18