문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top