python - /customer/1/ 'customer' 对象的 AttributeError 没有属性 'order_set'
问题描述
我正在尝试访问每个客户的订单,并以这种方式接近它:
def Customer(request, pk):
Customer = customer.objects.get(id=pk)
orders = Customer.order_set.all()
order_count = orders.count()
context = {
'orders': orders,
'customer': Customer,
'order_count': order_count,
}
return render(request, 'Inventory_Management/customer.html', context)
在 youtube 上,该男子说您可以使用订单型号名称访问与客户相关的订单,在我的情况下是“订单”,然后添加 _set 我这样做了,当我现在尝试查看客户时,我收到了这个错误: /customer/1/ 'customer' 对象的 AttributeError 没有属性 'order_set'。
相关型号
class order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
order_head = models.ForeignKey(order_header, blank=False, null=True, on_delete=models.SET_NULL)
items = models.ForeignKey(item, blank=False, null=True, on_delete=models.SET_NULL)
Quantity = models.CharField(max_length=100)
date_created = models.DateTimeField(auto_now_add=True, null=True)
total = models.CharField(max_length=100)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return 'Order Customer: {self.order_head.Buyer}'.format(self=self)
class customer(models.Model):
name = models.CharField(max_length=12, blank=False)
phone = models.CharField(max_length=12, blank=False)
email = models.CharField(max_length=50, blank=False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
相关视图
def Customer(request, pk):
Customer = customer.objects.get(id=pk)
orders = Customer.order_set.all()
order_count = orders.count()
context = {
'orders': orders,
'customer': Customer,
'order_count': order_count,
}
return render(request, 'Inventory_Management/customer.html', context)
相关网址
path('customer/<str:pk>/', Customer, name="customer"),
相关html
{% for customer in customers %}
<tr>
<td><a class="btn btn-sm btn-info" href="{% url 'customer' customer.id %}">View</a></td>
<td>{{customer.name}}</td>
<td>{{customer.phone}}</td>
</tr>
{% endfor %}
我不知道查询是否错误,但在 youtube 视频中,它正在工作。
解决方案
尝试这个..
def customer(request, pk):
customer = Customer.objects.get(id=pk)
orders = customer.order_set.all()
orders_count = orders.count()
context = {'customer':customer, 'orders':orders, 'orders_count':orders_count}
return render(request, 'accounts/customer.html',context)
推荐阅读
- javascript - Express JS 找不到参数 404
- swift - 从单个串行队列访问 Swift 实例变量会导致 Thread Sanitizer 问题
- java - 如何保存随机值
- css - React JS 在应用程序中插入我所有组件的样式,CSS 模块
- android - 带有标签/标签的照片的云存储架构/解决方案
- java - office365 中通过 SMTP 丢失的邮件标头
- javascript - 根据下拉列表中的选定选项更新 JS 中的变量
- bash - Shell脚本循环遍历文件夹中的所有文件并按数字顺序选择它们
- scala - NoClassDefFoundError:无法初始化类 org.apache.spark.package
- react-native - 在 onEndEditing 中设置 TextInput 状态