gpt4 book ai didi

python - Django同名多个输入插入到数据库

转载 作者:行者123 更新时间:2023-11-29 08:12:51 25 4
gpt4 key购买 nike

我有多个同名输入。使用 jquery 和 json 创建的 html。

HTML

<input type="text" name="product_id" value="xyz" />
<p class="left">
<label class="name">General</label>
<input type="hidden" value="2" name="location_id">
<input type="text" name="location_stock" placeholder="Quantity" class="text small right" value="5">
</p>
<p class="left">
<label class="name">warehouse 1</label>
<input type="hidden" value="5" name="location_id">
<input class="text small right" type="text" name="location_stock" placeholder="Quantity" value="7">
</p>
<p class="left">
<label class="name">warehouse 2</label>
<input type="hidden" value="6" name="location_id">
<input class="text small right" type="text" name="location_stock" placeholder="Quantity" value="8">
</p>

Json

$.getJSON(url, function(models) {
var options = '';
for (var i = 0; i < models.length; i++) {
options += '<p class="left"><label class="name">' + models[i].fields['name'] + '</label></span> <input type="hidden" name="location_id" value="' + models[i].pk + '" /><input type="text" class="text small right" placeholder="Quantity" name="location_stock" /></p>'
}
$(".widget.stock_details").append(options);
$("#stock_locations option:first").attr('selected', 'selected');
});

我想像这样将其插入到 mysql 表中

product_id = xyz , location_id=2, stock=5
product_id = xyz , location_id=5, stock=7
product_id = xyz , location_id=6, stock=8

方法是什么?

def add_new(request): 
product_id = request.POST.get('product_id')
location_id = request.POST.get('location_id')
stock = request.POST.get('location_stock')
p = Products_stock(product_id=product_id,location_id=location_id,stock=stock)
p.save()
response_data = {}
response_data['status'] = 'true'
response_data['message'] = 'success'
return HttpResponse(json.dumps(response_data), mimetype='application/javascript')

最佳答案

我从这里得到了一个解决方案 https://stackoverflow.com/a/4731596/1686265 。我就这样改变了看法。谢谢@Krish R。

def add_new(request): 
product_id = Products.objects.get(code=code).id
x = request.POST.getlist('location_id')
y = request.POST.getlist('location_stock')
zipped = zip(x, y)
for x, y in zipped:
z = Product_stocks(product_id=product_id,warehouse_id=x,stock=y)
z.save()
response_data = {}
response_data['status'] = 'true'
response_data['message'] = 'success'
return HttpResponse(json.dumps(response_data), mimetype='application/javascript')

关于python - Django同名多个输入插入到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21249620/

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