You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对比报价时触发list index out of range错误的技术求助

解决报价对比时的IndexError问题

问题描述

首次提交商品报价时触发IndexError,错误提示列表索引越界,报错代码行是尝试访问other_off[0].bid_price。移除价格对比条件提交数值后再恢复条件,代码可正常运行。

错误信息

IndexError at /bid/2/
list index out of range
File "C:\Users\N\Desktop\my own\views.py", line 98, in bid
elif bid_price <= other_off[0].bid_price :

原代码片段

def bid(request, bidid):                                                                                                                                                                          
    bid_price = Decimal(request.POST.get('bid_price', False))
    other_off = Bid_info.objects.filter(product=product).order_by('-bid_price')
    
    if Bid_info.objects.filter(product=product, seller=request.user).exists():
        messages.warning(request, "You've already made an offer for this product.")
    elif bid_price <= other_off[0].bid_price :
        messages.warning(request, "Your offer must be greater than other offers.")
    else:
        Bid_ = Bid_info(product=product, seller=request.user, bid_price=bid_price)

问题原因

首次提交报价时,对应商品的Bid_info表中没有任何历史报价数据,other_off返回的是空QuerySet。直接通过other_off[0]访问第一个元素时,因为列表为空,就会触发索引越界错误。

修复方案

在价格对比前先判断是否存在历史报价,修改后的代码如下:

def bid(request, bidid):                                                                                                                                                                          
    bid_price = Decimal(request.POST.get('bid_price', False))
    other_off = Bid_info.objects.filter(product=product).order_by('-bid_price')
    
    if Bid_info.objects.filter(product=product, seller=request.user).exists():
        messages.warning(request, "你已经为该商品提交过报价了。")
    # 先检查是否存在历史报价,再进行价格对比
    elif other_off.exists() and bid_price <= other_off[0].bid_price :
        messages.warning(request, "你的报价必须高于其他报价。")
    else:
        Bid_ = Bid_info(product=product, seller=request.user, bid_price=bid_price)
        Bid_.save()  # 补充保存操作,确保报价存入数据库
        messages.success(request, "报价提交成功!")

关键修改点

  • 增加other_off.exists()判断,确保只有存在历史报价时才执行价格对比逻辑
  • 首次提交无历史报价时,直接进入else分支创建新报价,避免触发索引错误

内容的提问来源于stack exchange,提问作者zahra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:21:06