Django-mptt 获取每个类别内项目的累积计数

发布于 2025-01-13 16:39:11 字数 2804 浏览 4 评论 0原文

我正在使用 django-mptt。

我正在尝试获取所有类别以及每个类别内的项目数。

但我收到此错误:

OperationalError at /items/
(1054, "Unknown column 'items_category.lft' in 'where clause'")

从我的 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 )

使用 print(categories.query) 生成的查询是:

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

我尝试修复查询生成器,直接在我的数据库上尝试它,似乎查询是正确的,但是语法非常错误。

正确且有效的查询是我刚刚删除了 `.

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'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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文