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

Django开发中bid=3、highest_bid=2000.6时bid>highest_bid返回True原因?

问题根因

所有通过request.POST获取的表单值默认均为字符串类型,你当前直接对两个字符串执行大小比较,Python会逐位对比字符的ASCII编码值:
字符串'3'的首字符ASCII编码远高于'2000.6'的首字符'2'的编码,因此会直接返回True,不会按照实际数值大小对比。

修复方案
  1. 先将两个值转换为数值类型后再做比较,同时增加异常校验处理非法输入
  2. 涉及金额的场景建议优先用Decimal代替float,避免浮点精度误差
  3. 【安全优化】不要从前端隐藏域传递highest_bid,用户可以通过浏览器调试工具篡改该值,建议直接在后端从数据库查询对应商品的当前最高出价,规避伪造风险

修正后的views.py代码参考:

# 可引入Decimal处理金额精度
from decimal import Decimal, InvalidOperation

# place bid
if 'bid' in request.POST:
    try:
        # 生产环境请删除下面这行,改为从数据库查询当前item的最高出价
        highest_bid = Decimal(request.POST.get("highest_bid", "0"))
        bid = Decimal(request.POST.get("bid", "0"))
    except (InvalidOperation, ValueError):
        # 处理非数字类的非法输入
        return redirect(reverse("listing-detail", args=[listing_id]))
    
    if bid > highest_bid:
        new_bid = Bids(bid_value=bid, bidder=self.request.user, item=item)
        new_bid.save()

return redirect(reverse("listing-detail", args=[listing_id]))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:24:03