js837
js837

Reputation: 133

Django in query

When using django querysets. Is is possible to use the in operation, or another method, to maintain a one-to-one mapping between objects.

For example I would like:

id_list = [12,2,33] Foo.objects.filter(id__in=id_list)

To preserve order and return None when one of the ids is missing, eg:

ret = [Foo(id=12), None, Foo(id=33)]

where Foo(id=2) doesn't exist.

At present, the only method I have of doing this is to create an intermediate dictionary. For example:

map = {o.id: o for o in Foo.objects.filter(id__in=id_list)}
ret = [map.get(id, None) for id in id_list]

Upvotes: 2

Views: 59

Answers (1)

Alasdair
Alasdair

Reputation: 308779

There isn't a simple way to fetch the instances in the order, and needing to returning None for missing objects makes it even trickier.

You can use in_bulk() to simplify your code slightly.

bulk_foos = Foo.objects.in_bulk(id_list)  # returns a dict of foos, keyed on id
ordered_foos = [bulk_foos.get(foo_id, None) for foo_id in id_list)]

Upvotes: 2

Related Questions