[英]AttributeError at /orders/ 'QuerySet' object has no attribute 'orderitem
I am working on a django project where I want to display all the orders of a customer.我正在开发一个 django 项目,我想在其中显示客户的所有订单。 This is my models.py:
这是我的models.py:
class Order(models.Model):
customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True)
date_ordered=models.DateTimeField(auto_now_add=True)
complete=models.BooleanField(default=False,null=True,blank=False)
transaction_id=models.CharField(max_length=100,null=True)
class OrderItem(models.Model):
product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True)
order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True)
quantity=models.IntegerField(default=0,null=True,blank=False)
date_added=models.DateTimeField(auto_now_add=True)
And this is my views.py:这是我的views.py:
def orders(request):
customer=request.user.customer
order=Order.objects.filter(customer=customer, complete=True)
items=order.orderitem.get(order=order)
return render(request,"orders.html",{'order':order,})
When I open this template it gives me the error: query set object has no attribute orderitem.当我打开此模板时,它给了我错误:查询集 object 没有属性 orderitem。 I want it to give me the orders for which complete=True and all the orderitems under that particular order so that I can iterate over them and show them in my template but that is not happening for me.
我希望它给我完整 = True 的订单以及该特定订单下的所有订单项,以便我可以遍历它们并在我的模板中显示它们,但这对我来说并没有发生。 PLease help.
请帮忙。 Any help would be appreciated.
任何帮助,将不胜感激。
Add related_name="order_items"
to the order
field in OrderItem
as follow.将
related_name="order_items"
添加到OrderItem
中的order
字段,如下所示。
order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True, related_name="order_items")
Now you can access the order_items
of an order like this现在您可以像这样访问订单的
order_items
order=Order.objects.filter(customer=customer, complete=True).first()
items = order.order_items
You can use this:你可以使用这个:
items=OrderItem.objects.all()
and in your template you can use a loop and give a if condition seeing your models like:在您的模板中,您可以使用循环并给出一个 if 条件来查看您的模型,例如:
{% for ord in orders %}
{% for item in items %}
{% if item.order.id == ord.id %}
This is not the most efficient way as it will iterate over all items in your database but it may work for you这不是最有效的方法,因为它会遍历数据库中的所有项目,但它可能对您有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.