[Answer]-How to add custom data to Django MPTT model for recursetree template tag

1👍

The recursetree tag calls .order_by on your queryset, if it’s actually a queryset.

This copies the queryset, does another query and re-fetches all the objects from the database. Your extra attribute no longer exists on the new objects.

The easiest way to fix this is probably to call list() on your queryset before passing it to recursetree. Then mptt will assume the ordering is already done and won’t re-order the queryset.

myModelList = list(myModel.objects.order_by('tree_id', 'lft'))
for i, obj in enumerate(myModelList):
    obj.myIntB = i

return render(
    request, 
    'myApp/myTemplate.html', 
    Context({"myModels": myModelList})
)

Leave a comment