如何循环遍历请求数据并将其作为一行提交到数据库中,用户可以提交多个描述、长度等,问题是在DB中创建大量行以获得上一个A1的正确格式,但用户可以提交1,1,1,1,1;A2,2,8,100等作为其动态添加表单)
descriptions = request.POST.getlist('description')
lengths = request.POST.getlist('lengthx')
widths = request.POST.getlist('widthx')
depths = request.POST.getlist('depthx')
quantitys = request.POST.getlist('qtyx')
for description in descriptions:
for lengt in lengths:
for width in widths:
for depth in depths:
for quantity in quantitys:
newquoteitem = QuoteItem.objects.create(
qdescription=description,
qlength=lengt,
qwidth=width,
qdepth=depth,
qquantity=quantity,
quote_number=quotenumber,
)
发布于 2022-11-11 09:08:13
优先解决方案
使用模板集。这正是他们所要处理的。
第二解
descriptions = request.POST.getlist('description')
正在返回所有描述的列表,因此假设有5,它迭代5次。现在,lengths = request.POST.getlist('lengthx')
是一个所有长度的列表,同样是其中的5个,所以它将迭代5次,而且由于它是嵌套在循环描述中的,所以是25次!
因此,尽管我仍然认为表单设置是可行的,但您可以尝试以下方法:
descriptions = request.POST.getlist('description')
lengths = request.POST.getlist('lengthx')
widths = request.POST.getlist('widthx')
depths = request.POST.getlist('depthx')
quantitys = request.POST.getlist('qtyx')
for i in range(len(descriptions)):
newquoteitem = QuoteItem.objects.create(
qdescription=descriptions[i],
qlength=lengths[i],
qwidth=widths[i],
qdepth=depths[i],
qquantity=quantitys[i],
quote_number=quotenumber,
)
在这里,如果有5个描述,那么len(descriptions)
将是5,并且有一个循环,它总共会迭代5次。
https://stackoverflow.com/questions/74405621
复制相似问题