简体   繁体   中英

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 aa 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?

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 (eg CharFields), not just id fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM