gpt4 book ai didi

python - 获取父表及其子表的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:48 24 4
gpt4 key购买 nike

我在父表和子表上有一对多关系。并尝试以 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.

关于python - 获取父表及其子表的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60275076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com