Django gets all child child models using django parameter set

I have a user model with a self-reference. Now I need to get all the children for this user.

class MyUser(AbstractBaseUser, PermissionsMixin):
      .....
      parent = models.ForeignKey('self', blank=True, null=True, related_name ='children')

User A has a child User B

User B has child C

Using C has a child of D

So, if I have User A as indicated, I want to get

User B, C, D as a result

How to do this using a django request?

+4
source share
2 answers

, . Selcuk AttributeError, ( ). , , clean.

from django.core.exceptions import ValidationError

class MyUser(AbstractBaseUser, PermissionsMixin):
    parent = models.ForeignKey('self', blank=True, null=True, 
                related_name="children")

    def get_all_children(self):
        children = [self]
        try:
            child_list = self.children.all()
        except AttributeError:
            return children
        for child in child_list:
            children.extend(child.get_all_children())
        return children

    def get_all_parents(self):
        parents = [self]
        if self.parent is not None:
            parent = self.parent
            parents.extend(parent.get_all_parents())
        return parents

    def clean(self):
        if self.parent in self.get_all_children():
            raise ValidationError("A user cannot have itself \
                    or one of its' children as parent.")
+2

, () :

class MyUser(AbstractBaseUser, PermissionsMixin):
    ...
    def get_all_children(self):
        children = []
        for u in self.children.all():
            children.append(u.get_all_children())
        return children

, ( ), .

0

All Articles