使用Flask-SQLAlchemy批量插入IGNORE

时间:2019-04-07 05:46:14

标签: python sqlalchemy

我正在尝试使用API​​收集的数据更新数据库,并且需要确保所有表都已更新。

有时候,我会收到数据库中已经存在的数据,所以我想执行INSERT IGNORE。

我当前的代码如下:

def update_orders(new_orders):

    entries = []
    for each_order in new_orders:

            shipping_id = each_order['id']
            title = each_order['title']
            price = each_order['price']
            code = each_order['code']
            source = each_order['source']
            phone = each_order['phone']
            category = each_order['delivery_category']
            carrier = each_order['carrier_identifier']

            new_entry = Orders(
                id=shipping_id,
                title=title,
                code=code,
                source=source,
                phone=phone,
                category=category,
                carrier=carrier,
                price=price
            )

            entries.append(new_entry)

    if len(entries) == 0:
        print('No new orders.')
        break
    else:   
        print('New orders:', len(entries))
        db.session.add_all(entries)
        db.session.commit()

当我从头开始创建数据库时,这很好用,但是如果有重复的数据,并且我无法提交插入,它将给我一个错误。

我已经阅读了一段时间,找到了一种使用prefix_with的解决方法:

    print('New orders:', len(entries))

    if len(entries) == 0:
        print('No new orders.')
    else:   
        insert_command = Orders.__table__.insert().prefix_with('OR IGNORE').values(entries)
        db.session.execute(insert_command)
        db.session.commit()

问题在于values(entries)是一堆对象: <shop.database.models.Orders object at 0x11986def0>是内存中的类实例对象,而不是类的实例。

有人对解决这个问题有什么建议吗? 可以随意提出其他方法,或者只是一种调整。

非常感谢。

1 个答案:

答案 0 :(得分:0)

您正在使用哪个数据库?在MySQL下,“ INSERT OR IGNORE”不是有效的语法,而是应该使用“ INSERT IGNORE”。我遇到了同样的情况,并使查询与以下对象一起工作:

insert_command = Orders.__table__.insert().prefix_with(' IGNORE').values(entries)
相关问题