我有自我参考的用户模型.现在我需要为给定的用户获取所有孩子.
class MyUser(AbstractBaseUser, PermissionsMixin):
.....
parent = models.ForeignKey('self', blank=True, null=True, related_name ='children')
用户A具有子用户B.
用户B有子用户C.
使用C有子用户D
因此,如果我有给定的用户A,那么我想得到
用户B,C,D作为结果
如何使用django查询?
最佳答案 派对有点晚了,但我碰到了同样的问题.塞尔丘克的答案引发了一个属性错误,我写了一个改进的函数(但对他们赞不绝口).对于我的用例,我还需要一种方法来查找所有父项,并且我确保通过在我的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.")