Python Django:如何以非恐怖的方式查询child、granchildren等记录
我试图返回Employees表中与用户具有嵌套关系的用户列表/筛选器。例如,我将员工绑定到他们的经理,我希望能够查询该经理下的所有员工(这包括主经理下的任何其他经理下的任何员工)。因此,如果用户Python Django:如何以非恐怖的方式查询child、granchildren等记录,python,django,django-models,django-orm,Python,Django,Django Models,Django Orm,我试图返回Employees表中与用户具有嵌套关系的用户列表/筛选器。例如,我将员工绑定到他们的经理,我希望能够查询该经理下的所有员工(这包括主经理下的任何其他经理下的任何员工)。因此,如果用户Bob有两个直接下属,Sally和Brian。而Brian有2名直接下属,Sally有3名直接下属。我希望Bob能够看到所有7名员工。现在,我能让它工作的唯一方法是通过一个可怕的序列,如下所示..我希望他们的方法更简单/更有效 manager = Employees.objects.filter(
Bob
有两个直接下属,Sally
和Brian
。而Brian
有2名直接下属,Sally
有3名直接下属。我希望Bob能够看到所有7名员工。现在,我能让它工作的唯一方法是通过一个可怕的序列,如下所示..我希望他们的方法更简单/更有效
manager = Employees.objects.filter(manager_id=request.user.id).values('manager')
employee_ids = list(Employees.objects.filter(manager=manager.first()['manager']).values_list('employee', flat=True))
employees = [User.objects.get(id=i).username for i in employee_ids]
grandchildren = []
for i in employees:
user_id = User.objects.get(username=i).id
child = list(Employees.objects.filter(manager=user_id).values_list('employee', flat=True))
grandchildren.append(child)
children = list(chain.from_iterable(grandchildren))
for i in children:
user_id = User.objects.get(id=i).id
child = list(Employees.objects.filter(manager=user_id).values_list('employee', flat=True))
grandchildren.append(child)
grandchildren = list(chain.from_iterable(grandchildren))
for i in grandchildren:
employees.append(User.objects.get(id=i).username)
employees = list(set(employees))
对不起,你的代码看起来很糟糕。首先,我指的是太多的DB查询(大多数查询都是非优化的,甚至不需要) 根据您的描述,我建议您尝试以下方式:
manager_id = request.user.id
children_ids = list(
Employees.objects.filter(manager_id=manager_id).values_list('employee', flat=True)
)
grandchildren_ids = list(
Employees.objects.filter(manager_id__in=children_ids).values_list('employee', flat=True)
)
# If you want to go deeper, do this in a loop and stop once an empty list of IDs is fetched
# (which means that there are no descendants anymore)
# Combine all IDs and finally fetch the actual users
# (do it only once, and fetch all the users in a single query, not one by one)
employees_ids = children_ids + grandchildren_ids
employees = User.objects.filter(id__in=employees_ids)
旁白:这是一个笑话吗user\u id=user.objects.get(id=i.id
?:)