user1427661
user1427661

Reputation: 11774

Find an object with a matching key in a list of objects

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

Answers (2)

alko
alko

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

jonafato
jonafato

Reputation: 1605

return bundle.obj.customers.filter(id=bundle.request.user.id).exists()

See the docs on the exists method.

Upvotes: 2

Related Questions