Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get objects for many IDs

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?

like image 744
rectangletangle Avatar asked Apr 15 '14 23:04

rectangletangle


1 Answers

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.

like image 184
Shaun O'Keefe Avatar answered Sep 28 '22 01:09

Shaun O'Keefe