Django-mptt order

2019-03-13 10:15发布

问题:

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

My model:

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

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.

回答1:

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

So something like this:

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

    class MPTTMeta:
        order_insertion_by = ['name']

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



回答2:

With recent mptt versions (e.g. 0.8.7) you should use the TreeForeignKey field:

from mptt.models import MPTTModel
from mptt.fields import TreeForeignkey

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

    class MPTTMeta:
        order_insertion_by = ['name']