0

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

handros
  • 597
  • 1
  • 5
  • 14

1 Answers1

1

Check exists() and lookups spanning relationships

Order.objects.filter(contact=contact, 
                     order_item__product=cartitem.product_id).exists()
okm
  • 23,575
  • 5
  • 83
  • 90
  • Thanks okm! This is what I needed ultimately: **Order.objects.filter(contact=contact, orderitem__product=cartitem.product_id).exists()** I'm not sure why product_id had to become product, but in any event it works now. – handros Apr 28 '12 at 18:59
  • @user1294974 fixed. No idea why `_id` does not work, it normally should for FK. But yes `product` always works and shorter in code. – okm Apr 29 '12 at 05:32
  • @user1294974 Welcome to Stack Overflow! Now that you've solved your problem with okm's answer, make sure to mark it as accepted using the green checkmark. – Danica Apr 29 '12 at 06:53