[Django]-Django – Models – Recursively retrieve parents of a leaf node

7πŸ‘

βœ…

I have not tested this but it should work:

class CustomUser(models.Model):
    user = models.OneToOneField(User)
    slug = models.SlugField(max_length=35, unique=True,help_text="URI dell'utente che appare sul browser")
    team = models.CharField(max_length=100, null=False, verbose_name="Team")
    area = models.CharField(max_length=100, null=False, verbose_name="Area")
    line_manager = models.ForeignKey('self', null=True, blank=True,related_name='parent')

    def get_linemanagers(self):
        if self.line_manager is None:
            return CustomUser.objects.none()
        return CustomUser.objects.filter(pk=self.line_manager.pk) | self.line_manager. get_linemanagers()

Hope it helps.

πŸ‘€user4426017

Leave a comment