Search code examples
pythondjangodjango-mptt

How to know level of every child relative to main parent in django-mptt?


I use django-mptt application in my project. Let me try to explain the problem.

views.py:

user_profile = Profile.objects.get(user=self.request.user)
referrals = user_profile.get_descendants().filter(level__lte=profile.level + 3)

With the help of next code I show descendants of current user (only 3 level) and want to know level of every child relative to parent. In fact in database that user can have child with level more than 3.

In template user A has next tree with 3 level

user A
 user B (level 1)
  user C (level 2)
    user D (level 3)

In fact in dababase user A has tree more than 3 level as you see. In my case it's 5.

user A
 user B (level 1)
  user C (level 2)
    user D (level 3)
      user E (level 4)
        user F (level 5)

Now when user D open his page in template he see his own descendants:

user D
 user E
  user F

I want to know level of user E and F relative to user D. How to make it?

I tried in views.py:

for referral in referrals:
   print(referral.level)

This code return me level 4 for user E and level 5 for to user F.


Solution

  • The relative level, is the level of the referral minus the level of the "current" userprofile. We can thus use referral.level - userprofile.level.

    If you however want to annotate all these objects with a relative_level, we can use Django's ORM:

    from django.db.models import F
    
    (user_profile.get_descendants()
                 .filter(level__lte=profile.level + 3)
                 .annotate(relative_level=F('level') - profile.level))

    So then all the descendants will have an extra attribute .relative_level that will containt the relative level.