Question

I'm pretty sure the following code can be done much more efficiently using querysets. I just don't know how. Any suggestions? Here's my code:

orders = Order.objects.filter(contact=contact)
for order in orders:
    for item in order.orderitem_set.all():
        if cartitem.product_id == item.product_id:
            return True
return False

Many thanks, Thomas

Was it helpful?

Solution

Check exists() and lookups spanning relationships

Order.objects.filter(contact=contact, 
                     order_item__product=cartitem.product_id).exists()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top