首页 > 解决方案 > 为什么 django 会抛出像“'function' object has no attribute 'order_set'”这样的错误?

问题描述

我编辑了views.py,之后它会抛出如下截图所示的错误。 在此处输入图像描述

这是代码。
/apps/views.py 包含

from django.shortcuts import render
from django.http import HttpResponse
from .models import *
    
def customer(request, pk):
  customers = Customer.objects.get(id=pk)
    
   order = customer.order_set.all()
    
   context={'customers':customers, 'order':order}
   return render(request, 'accounts/customer.html',context)

/templates/apps/name.html 包含此代码以将数据从模型呈现到模板。

{% for i in order %}
 <tr>
    <td>{{i.product}}</td>
    <td>{{i.product.category}}</td>
    <td>{{i.date_created}}</td>
    <td>{{i.status}}</td>
    <td><a href="">Update</a></td>
    <td><a href="">Remove</a></td>
 </tr>
{% endfor %}

我认为这个错误与views.py中的order_ser有关,但我不知道如何修复它。

标签: djangodjango-modelsdjango-viewsdjango-templates

解决方案


你写了customers = customer.objects.get(id=pk),然后你用了customer.order_set,这里customer指的是customer函数。你应该使用customer

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from .models import *
    
def customer(request, pk):
    #      ↓ without s
    customer = get_object_or_404(Customer, id=pk)
    order = customer.order_set.all()
    
    context={'customer': customer, 'order':order}
    return render(request, 'accounts/customer.html', context)

注意:通常最好使用get_object_or_404(…)[Django-doc],然后直接使用.get(…)[Django-doc]。如果对象不存在,例如因为用户自己更改了 URL,get_object_or_404(…)则将导致返回HTTP 404 Not Found响应,而 using .get(…)将导致HTTP 500 Server Error


推荐阅读