How would you sort a django mptt tree?

2020-06-27 01:58发布

Imagine that I have an mptt tree of objects and their population like:

Animal, 60

  • aardvark, 30
  • bobcat, 20
  • chipmunk, 10

Vegetable, 6

  • apple, 1
  • beet, 2
  • cauliflower, 3

Mineral 0

How would you sort the above by population on each sublevel? I want to get to:

Animal, 60

  • aardvark, 30
  • bobcat, 20
  • chipmunk, 10

Vegetable, 6

  • cauliflower, 3
  • beet, 2
  • apple, 1

Mineral 0

I am building off of mptt in django.

3条回答
Fickle 薄情
2楼-- · 2020-06-27 02:29

I've just solved a similar issue. You can use an order_by, but not simply by the field you want to sort by:

MyModel.tree.all().order_by('tree_id', 'level', 'your_sort_field')
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-06-27 02:38

Try to add it in the models.py Meta Class.

Or on a subsidiary QuerySet

查看更多
可以哭但决不认输i
4楼-- · 2020-06-27 02:42

Should an order_by simply work?

YourModel.tree.filter(your=stuff).order_by('order')
查看更多
登录 后发表回答