I'm using django-mptt.
I'm trying to get all categories with the count of items inside each category.
But I get this error:
OperationalError at /items/
(1054, "Unknown column 'items_category.lft' in 'where clause'")
From my view.py
categories = Category.objects.add_related_count(
Category.objects.all(), # Queryset
Item, # Related mobile
'category', # Name of the foreignkey field
'count', # Name of the property added to the collection
cumulative=True) # Cumulative or not.
print(categories)
model.py
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=50, null=True, blank=True, )
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by=['name']
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
class Meta:
unique_together = ('slug', 'parent',)
verbose_name_plural = "categories"
class Item(models.Model):
category = TreeForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True)
name = models.CharField(max_length=250 )
Using print(categories.query)
query generated is:
SELECT `items_category`.`id`, `items_category`.`name`, `items_category`.`slug`, `items_category`.`parent_id`, `items_category`.`lft`, `items_category`.`rght`, `items_category`.`tree_id`, `items_category`.`level`, (SELECT count(*) FROM (SELECT U0.`id` FROM `items_item` U0 INNER JOIN `items_category` U1 ON (U0.`category_id` = U1.`id`) WHERE (U1.`lft` >= `items_category`.`lft` AND U1.`lft` <= `items_category`.`rght` AND U1.`tree_id` = `items_category`.`tree_id`)) _count) AS `count` FROM `items_category` ORDER BY `items_category`.`tree_id` ASC, `items_category`.`lft` ASC
I tried to fix query generator trying it directly on my database and seems query is correct but syntax is very wrong.
The correct and working query is that I just removed `.
SELECT items_category.id, items_category.name, items_category.slug, items_category.parent_id, items_category.lft, items_category.rght, items_category.tree_id, items_category.level,
(
SELECT count(*)
FROM (
SELECT U0.id
FROM items_item U0
INNER JOIN items_category U1 ON ( U0.category_id = U1.id)
WHERE (U1.lft >= items_category.lft
AND U1.lft <= items_category.rght
AND U1.tree_id = items_category.tree_id
)
) _count
) AS count
FROM items_category
ORDER BY items_category.tree_id
ASC, items_category.lft ASC