Reputation: 11774
I have code that looks like this (.customers refers to a list of Django models named Customer):
return bundle.request.user.id in bundle.obj.customers.all()
This doesn't work because it's checking an id against a list of Customer objects. I want something that offers similar optimized evaluation to Django's all() but will return true if one of the customers in the list has a matching id. Is there an elegant way to achieve this?
Upvotes: 0
Views: 126
Reputation: 48317
With as few modifications as possible:
return bundle.request.user.id in {x.id for x in bundle.obj.customers.all()}
or if all()
is not yet evaluated, and indexes are present in db, following query will be faster
return bundle.obj.customers.filter(id = bundle.request.user.id).exists()
Upvotes: 0