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

Django报错MultipleObjectsReturned:编辑采购记录时get()返回多条数据

解决Django中get() returned more than one items错误

嘿,我看你在编辑采购记录的时候碰到了这个头疼的错误,咱们来一步步解决它:

问题根源

你在edit_purchase视图里写了entry = get_object_or_404(Purchases),这行代码没有给任何筛选条件,Django会尝试获取所有采购记录,但你的数据库里有3条匹配的记录。而get()方法要求只能返回单个对象,所以直接触发了MultipleObjectsReturned错误——简单说就是:你没告诉Django要编辑哪一条记录!

具体修复步骤

1. 先给URL加上记录ID参数

打开你的urls.py,把编辑页面的URL改成带ID的形式,这样才能把要编辑的记录ID传递到视图里:

path('edit_purchase/<int:entry_id>/', views.edit_purchase, name='edit_purchase'),

2. 更新视图函数,通过ID获取单条记录

修改views.py里的edit_purchase函数,让它接收entry_id参数,并用这个ID精准定位要编辑的记录:

def edit_purchase(request, entry_id):
    # 用entry_id筛选,确保只获取一条记录
    entry = get_object_or_404(Purchases, id=entry_id)
    
    # 删掉这行:purchase = entry.purchase —— 你的模型里根本没有purchase字段,留着会报错!
    if request.method != 'POST':
        # 初始请求,用现有记录填充表单
        form = PurchasesForm(instance=entry)
    else:
        # 处理POST提交的数据
        form = PurchasesForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('geo_gas:purchases'))
    
    # 原来的context里的purchases没定义,要么去掉要么按需查询,这里先去掉避免报错
    context = {'entry': entry, 'form': form}
    return render(request, 'geo_gas/edit_purchase.html', context)

3. 修复模板里的链接和表单提交地址

  • 在你的采购列表页面(比如purchases.html)里,每个编辑按钮/链接要带上对应的记录ID:
    {% for purchase in purchases %}
        <p>{{ purchase.bottle }} <a href="{% url 'geo_gas:edit_purchase' purchase.id %}">编辑</a></p>
    {% endfor %}
    
  • 然后在edit_purchase.html里,表单的action要改成带当前记录ID的URL:
    <form action="{% url 'geo_gas:edit_purchase' entry.id %}" method='post'>
        {% csrf_token %}
        {{ form.as_p}}
        <button name="Submit">save changes</button>
    </form>
    

额外优化建议

  • 你的模型里的bottle_total、transportation_cost、total_cost这些是数值,用CharField不合适,建议改成DecimalField(支持小数)或者IntegerField:
    bottle_total = models.DecimalField(max_digits=10, decimal_places=2)
    transportation_cost = models.DecimalField(max_digits=10, decimal_places=2)
    total_cost = models.DecimalField(max_digits=10, decimal_places=2)
    
  • 确保你的PurchasesForm是正确的ModelForm,比如:
    from django import forms
    from .models import Purchases
    
    class PurchasesForm(forms.ModelForm):
        class Meta:
            model = Purchases
            fields = ['bottle', 'bottle_purchased', 'bottle_total', 'transportation_cost', 'total_cost']
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:25:01