【问题标题】:Why am i getting peewee.OperationalError为什么我得到 peewee.OperationalError
【发布时间】:2021-03-05 05:15:11
【问题描述】:

我正在尝试使用名为 Product 的表将“items”、“price”、“stock”和最终“dates”添加到我的 inventory.db 中。如何在不轰炸代码的情况下获取这些数据。由于我是这种类型的新手,请详细说明我做错了什么。

另外,我如何为每个单独的产品名称创建一个 ID?我一直在寻找,但我没有看到我在寻找什么。

这是我正在使用的:https://github.com/OXDavidXO/Python-Project-4/blob/main/app.py

这是搞砸的部分:

inventory = {
    'items': food_names,
    'price': food_price,
    'stock': food_stock,
    'dates': dates_added
}


def add_products():

    try:
        food_item = Product.create(product_names = inventory['items'])
        food_item.save()
    except IntegrityError:
        food_product = Product.get(product_names = inventory['items'])

【问题讨论】:

  • edit问题包含完成错误回溯。
  • “轰炸代码”是什么意思?由于您似乎对此不熟悉,我建议您只做一个简单的for 循环并为您要添加的每个单独产品调用Product.create()。在基本实现正常工作之前,不要担心优化(例如批量创建)。

标签: python python-3.x sqlite orm peewee


【解决方案1】:

我猜你正在使用 Postgresql,虽然你没有提到什么 db.当您进入不良事务状态时(例如,通过捕获完整性错误),您需要回滚到良好状态才能继续。正确的做法是:

try:
    with db.atomic() as tx:
        food_item = Product.create(product_names = inventory['items'])
        # calling save() again is redundant, removed.
except IntegrityError as exc:
    food_item = Product.get(product_names = inventory['items'])

否则,请发布实际的回溯和错误消息。没有这些信息就很难调试。

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 2021-08-04
    • 2019-03-28
    • 2021-08-27
    • 2021-10-23
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多