Django同名多个输入插入到DB

时间:2014-01-21 05:08:20

标签: python mysql django

我有多个同名输入。用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')

1 个答案:

答案 0 :(得分:2)

我从这里得到了一个解决方案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')