Django-mptt order

梦想与她 提交于 2019-12-03 00:23:21

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.

P.K

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']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!