djangosatchmo

Using querysets properly


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


Solution

  • Check exists() and lookups spanning relationships

    Order.objects.filter(contact=contact, 
                         order_item__product=cartitem.product_id).exists()