我在父表和子表上有一对多关系。并尝试以 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)
当我尝试在其父
字典中附加子表
时,问题就开始了。但在上面的方式中,我只是将所有子项附加到每个父项字典中......
还有其他更简单的方法可以实现这一点吗?
问题出在您的 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.
我是一名优秀的程序员,十分优秀!