Django get objects for many IDs

django, django-queryset, python

Solution

There's an __in (documentation here) field lookup that you can use to get all objects for which a certain field matches one of a list of values

objects = SomeModel.objects.filter(id__in=id_set)

Works just the same for lots of different field types (e.g. CharFields), not just id fields.

Problem

I have a set of ID's that I'd like to retrieve all of the objects for. My current solution works, however it hammers the database with a a bunch of `get` queries inside a loop. ``` objects = [SomeModel.objects.get(id=id_) for id_ in id_set] ``` Is there a more efficient way of going about this?

Original source