Django-mptt命令 [英] Django-mptt order

查看:94
本文介绍了Django-mptt命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我使用django-mptt作为类别.

In my project I am using django-mptt for categories.

我的模特:

class Category(models.model):
    name = models.CharField()
    parent = models.ForeignKey("self", blank=True, null=True,
                           related_name="sub_category")
    nav_order = models.IntegerField(null=False, blank=False, default=0)
    # unsure need nav_order column in DB

    class Meta:
        verbose_name_plural = 'Categories'
mptt.register(Category)

我需要有能力像这样获得当前类别的订单:

And I need to have ability get order for current category like this:

Category                Navigation order(one column)

CatA                      0
|-subcat11                 0
  |-sub11a                    0
  |-sub11b                    1
  \-sub11c                    2
\-subcat12                 1
CatB                      1  
|-subcat21                 0
|-subcat22                 1
\-subcat23                 2
  \-sub23a                    0
CatC                      2

如何在创建/移动元素时快速填充/重新计算订单列. 或按类别的方法计算Category.objects.get(name='sub11b').get_order()应该返回1.

How can I quickly fill/recalculate order column on creating/moving elements. Or calculate it by Category's method Category.objects.get(name='sub11b').get_order() should return 1.

推荐答案

定义模型时,可以使用"order_insertion_by"指定排序.

When defining the model you can specify the ordering with "order_insertion_by".

是这样的:

class Category(MPTTModel):
    name = models.CharField()
    parent = models.ForeignKey("self", blank=True, null=True, 
             related_name="sub_category")

    class MPTTMeta:
        order_insertion_by = ['name']

然后,您可以使用Category.tree.rebuild()重建数据库,该数据库应遵守指定的顺序.

Then you can rebuild your database with Category.tree.rebuild() which should respect the ordering specified.

这篇关于Django-mptt命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆