简体   繁体   中英

Django-mptt order

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.

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.

With recent mptt versions (eg 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM