如何避免在python中使用for循环将相同的数据添加到数据库中

时间:2015-04-30 21:55:32

标签: python sqlalchemy

我想知道如何将所有行插入db。

HTML code:

 <html>
    <label> Selector Name </label>
     <input type="textbox" value="Anu" name="selector_name"/>
    </label> 
    <label> Product Ids </label>
     <input type="textbox" value="1,2,3" name="product_ids"/>
 </html>

Python函数:

        selector =  parms['selector_name']
        product_id = parms['product_ids']
        prodids = product_id.split(",")
        for i in range(0,len(prodids)):
            product = Product.query.filter_by(id=imgids[i]).first_or_404()
            if product:
                product    = ProductSelector([product])
                selector.images.append(product)
         db.session.add(selector)     
         db.session.commit()

以上代码尝试多次添加相同的产品,这是不允许的。如何在不添加相同产品的情况下添加多个产品。

追溯:

  sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value 
  violates unique constraint "product_selector_pkey"

  DETAIL:  Key (id)=(82) already exists.
 'INSERT INTO product_selector (id) VALUES (%(id)s)' ({'id': 82}, {'id': 
   82}, {'id': 
   82})

1 个答案:

答案 0 :(得分:0)

当存在IntegrityError异常时,您可以传递它。这将跳过该记录并处理下一个记录,等等,当它发现此异常时。确保你输入了IntergrityError。

from sqlalchemy.exc import IntegrityError


    try:
        selector =  parms['selector_name']
        product_id = parms['product_ids']
        prodids = product_id.split(",")
        for i in range(0,len(prodids)):
            product = Product.query.filter_by(id=imgids[i]).first_or_404()
            if product:
                product    = ProductSelector([product])
                selector.images.append(product)
         db.session.add(selector)     
         db.session.commit()
     except IntegrityError:
         print "Duplicate Value entered"
         pass