首页 > 解决方案 > /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 视频中,它正在工作。

标签: pythonpython-3.xdjangodjango-querysetattributeerror

解决方案


尝试这个..

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) 

推荐阅读