django - 为什么 django 会抛出像“'function' object has no attribute 'order_set'”这样的错误?
问题描述
这是代码。
/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有关,但我不知道如何修复它。
解决方案
你写了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。
推荐阅读
- docusignapi - DocuSign 仍然支持 grant_type=password 吗?
- jquery - Datepicker 在动态创建的输入中不起作用
- javascript - 重新加载特定div时如何停止闪烁
- c# - 为什么自动重新编译不适用于 Visual Studio asp.net core mvc 项目中的 C# 类?
- opengl-es - 将 glsl 模与 uint 一起使用
- python-3.x - 处理文件夹中的多个 xml
- visual-studio - VS 测试在 Azure DevOps 中失败,而所有测试都成功了
- android - 如何使用 recyclerview 修复“期望成员声明”
- python - How can I use logistic regression in sklearn for continuous but bounded dependent variable?
- python - request.method 在 Flask 中默认为 GET