You need to enable JavaScript to run this app. 为什么Django抛出“'function'对象没有'order_set'属性”的错误?
优惠活动
大模型
产品
解决方案
定价
更多

为什么Django抛出“'function'对象没有'order_set'属性”的错误?

错误截图

问题修复方案

错误原因

你之前判断问题和order_set相关的方向是对的,但order_set本身的写法没有问题,错误出在下面两个细节:

  • 变量引用错误:你将查询到的Customer实例赋值给了名为customers的变量,但后续调用order_set时使用了不存在的变量customer(缺少末尾的s)
  • 缩进不规范:order = customer.order_set.all()这行存在多余的前置空格,缩进和上一行不一致,会触发Python语法错误

修复代码

修正后的/apps/views.py代码

from django.shortcuts import render
from django.http import HttpResponse
from .models import *
    
def customer(request, pk):
    # 这里直接将变量名改为customer更符合单条实例的语义,避免拼写混淆
    customer = Customer.objects.get(id=pk)
    # 使用正确的实例变量调用反向关联order_set
    order = customer.order_set.all()
    
    context={'customer': customer, 'order': order}
    return render(request, 'accounts/customer.html', context)

模板调整说明

你现有模板中遍历order的代码无需调整,如果按照上面的代码修改了context中Customer实例的key为customer,后续需要调用客户属性时对应使用customer作为变量名即可。

额外注意

你当前提供的模板路径为/templates/apps/name.html,但视图中渲染的模板路径为accounts/customer.html,请确认二者路径匹配,避免后续出现模板不存在报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 08:48:03