How would you sort a django mptt tree?

穿精又带淫゛_ 提交于 2019-12-05 03:43:15

问题


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.


回答1:


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')



回答2:


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

Or on a subsidiary QuerySet




回答3:


Should an order_by simply work?

YourModel.tree.filter(your=stuff).order_by('order')


来源:https://stackoverflow.com/questions/870821/how-would-you-sort-a-django-mptt-tree

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