how do I get all the product list that's been ordered in template

Viewed 26

how do I filter all the objects associated with "orderitem" for a specific user, so when someone orders a couple of products I want to show the ordered products in the template, right now I'm getting "The QuerySet value for an exact lookup must be limited to one result using slicing". would really appreciate your help, thx!

models.py

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)

class Product(models.Model):
    name = models.CharField(max_length=150)
    description = models.TextField()

views.py

def orders(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        orders = Order.objects.filter(customer=customer)
        orderitems = OrderItem.objects.filter(order=orders)
    else:
        print('error')
    context = {"orderitems": orderitems}
    return render(request, 'accounts/orders.html', context)

HTML

    {% for orderitem in orderitems %}
        <div class="ordered-view">
            
            <div class="order">{{ orderitem.product.name }}</div>
            <div class="date">dummydata</div>
            <div class="status">dummydata</div>
            <div class="total">dummydata</div>

        </div>
    {% endfor %}
1 Answers

You filter with:

from django.contrib.auth.decorators import login_required

@login_required
def orders(request):
    orderitems = OrderItem.objects.filter(
        order__customer__user=request.user
    ).select_related('product')
    context = {'orderitems': orderitems}
    return render(request, 'accounts/orders.html', context)

The .select_related(…) clause [Django-doc] will avoid hitting the database each time when you fetch the .product of the orderitem.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

Related