Django-mptt order

In my project, I use 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 be able to get the order for the current category as follows:

 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 to quickly fill / recount an order column when creating / moving items. Or compute it using the Category Category.objects.get(name='sub11b').get_order() method Category.objects.get(name='sub11b').get_order() should return 1.

+8
python django django-mptt
source share
2 answers

When defining a model, you can specify the order using "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 using Category.tree.rebuild() , which should be in the order specified.

+10
source share

In recent versions of mptt (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'] 
+2
source share

All Articles