rohit bumrah
rohit bumrah

Reputation: 236

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. This is my 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:

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. 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. PLease help. Any help would be appreciated .

Upvotes: 1

Views: 1314

Answers (2)

VATSAL JAIN
VATSAL JAIN

Reputation: 581

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:

{% 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

Upvotes: 1

mehdy
mehdy

Reputation: 3374

Add related_name="order_items" to the order field in OrderItem as follow.

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=Order.objects.filter(customer=customer, complete=True).first()
items = order.order_items

Upvotes: 2

Related Questions