使用其子表获取父表的正确方法



我在父表和子表上有一对多关系。并尝试将其子表作为json来获取父表。

我试过下面这样的东西。

if (request.method == "GET"):   
parents = Parent.objects.all()
datas = []
childTables = []
for parent in parents:
#fetching parent first and creating DICT for json
#also creating an array for the child tables
parentDict = {
"id": parent.id,
"project_name": parent.project_name,
childTables: childTables,
}
#then fetching child tables NO problem at this part as well.
childs = parent.child_set.filter(parent_id=parent)
for child in childs:
#creating a DICT FOR THE json.
childDict = {
"id":child.id,
"ad_kind":child.ad_kind,
"parent_id":child.parent_id,
}
#i am trying to append project's childs into ParentDict 
#but still it's appending all childs into every ParentDict...
#not just its parent's childs.
parentDict["childTables"].append(childDict)

#at last append all parent table inside an array and send it as JSON. 
datas.append(parentDict)
return JsonResponse(datas, safe=False)

当我试图将child tables附加到它的parent字典中时,问题就开始了。但按照上面的方式,我只是将所有子字典附加到每个父字典中。…

还有其他更简单的方法可以实现这一点吗?

问题出在childTables数组上。你应该把它放在父循环中,如果你这样做了,它会在每个循环中更新。然后你就可以得到预期的结果。

for parent in parents:
#childTable array placed in here.
#to renew on each loop.
childTable = []
parentDict = {
"id": parent.id,
"project_name": parent.project_name,
childTables: childTables,
}
#... the rest is fine. 

Python列表是可变的,并且您只在父循环之前创建了一个"childTables">列表实例。引用childTables的字典键引用原始列表,因此每次添加到列表中都会将值附加到同一列表中。

要解决这个问题,只需在每个父迭代上创建一个新列表:

for parent in Parent.objects.all():
parentDict = {
"id": parent.id,
"project_name": parent.project_name,
childTables: [],
}

顺便说一句,这不是将Django查询集转换为JSON对象的最佳方式。为此,我建议使用django-rest框架。

最新更新